Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix concurrency bug #26

Merged
merged 4 commits into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions cryptography-providers/jdk/src/jvmMain/kotlin/pooling.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@ internal sealed class Pooled<T>(protected val instantiate: () -> T) {
private val pooled = ArrayDeque<T>()

override fun get(): T {
synchronized(this) {
pooled.firstOrNull()
}?.let { return it }

return instantiate()
return synchronized(this) {
pooled.removeLastOrNull()
} ?: instantiate()
}

override fun put(value: T) {
Expand Down
33 changes: 33 additions & 0 deletions cryptography-providers/jdk/src/jvmTest/kotlin/PoolingTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package dev.whyoleg.cryptography.providers.jdk

import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class PoolingTest {

@Test
fun testSequentialAccessOnCachedPoolShouldReuseInstance() {
var instantiateCount = 0
val pool = Pooled.Cached { instantiateCount++; Any() }
repeat(3) {
pool.use { }
}
assertEquals(1, instantiateCount)
}

@Test
fun testConcurrentAccessOnCachedPoolShouldNotReuseInstances() = runTest {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while testing concurrent access is fine, I would say that we don't really need it here.
We can easily write a sequential test here, something like:

pool.use { i1 -> pool.use { i2 -> pool.use { i3 -> }}}

So let's keep both sequential and concurrent variant.

Additionally it would be good to not only count instantiate call, but to check, that instances are different.
So f.e make instance an Int instead of object and save instantiateCount there. And then assert, that the instances used in use are different.
And then, we are good to go!

var instantiateCount = 0
val pool = Pooled.Cached { instantiateCount++; Any() }
pool.use { } // prime the pool with 1 instance; we should not be able to reuse that instance for all 3 concurrent usages below
List(3) {
launch {
pool.use {
delay(1000)
}
}
}.joinAll()
assertEquals(3, instantiateCount)
}
}