Skip to content

Fix concurrency bug #26

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

Merged
merged 4 commits into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
50 changes: 50 additions & 0 deletions cryptography-providers/jdk/src/jvmTest/kotlin/PoolingTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package dev.whyoleg.cryptography.providers.jdk

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

class PoolingTest {

@Test
fun testSequentialUseCachedPool() {
val pool = Pooled.Cached(::Any)
val first = pool.use { it }
val second = pool.use { it }
assertSame(first, second)
val third = pool.use { it }
assertSame(second, third)
}

@Test
fun testOverlappingUseCachedPool() {
val pool = Pooled.Cached(::Any)
val first = pool.use { it }
pool.use { i1 ->
assertSame(first, i1)
pool.use { i2 ->
assertNotSame(i1, i2)
pool.use { i3 ->
assertNotSame(i2, i3)
}
}
}
}

@Test
fun testConcurrentUseCachedPool() = runTest {
val pool = Pooled.Cached(::Any)
val first = pool.use { it }
val instances = List(3) {
async {
pool.use { instance ->
delay(1000)
instance
}
}
}.awaitAll()
assertSame(first, instances[0])
assertNotSame(instances[0], instances[1])
assertNotSame(instances[1], instances[2])
}
}