Skip to content

Commit

Permalink
Fix concurrency issue in jdk provider (#26)
Browse files Browse the repository at this point in the history
(cherry picked from commit 2837434)
  • Loading branch information
emeasure-github-private authored and whyoleg committed May 21, 2024
1 parent 138bb70 commit 127ee1d
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 5 deletions.
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])
}
}

0 comments on commit 127ee1d

Please sign in to comment.