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 issue for Single definitions #914

Merged
merged 3 commits into from
Oct 8, 2020
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
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ class SingleInstanceFactory<T>(koin: Koin, beanDefinition: BeanDefinition<T>) :

@Suppress("UNCHECKED_CAST")
override fun get(context: InstanceContext): T {
if (!isCreated()) {
value = create(context)
synchronized(this) {
if (!isCreated()) {
value = create(context)
}
}
return value ?: error("Single instance created couldn't return value")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.koin.core

import org.junit.Assert.assertEquals
import org.junit.Test
import org.koin.Simple
import org.koin.dsl.koinApplication
import org.koin.dsl.module
import java.util.concurrent.Callable
import java.util.concurrent.Executors

class SingleConcurrencyTest {

@Test
fun `never creates two instances from different threads`() {
val executor = Executors.newFixedThreadPool(8)
// This test is repeated many times, because it only fails a very small % of times
repeat(3000) { repetition ->
val app = koinApplication {
modules(module {
single { createComponent() }
})
}

val numberOfInstances = (1..50)
.map { executor.submit(Callable { app.koin.get<Simple.ComponentA>() }) }
.map { it.get() }
.distinctBy { it.toString() }
.count()


assertEquals(
"More than one instance created concurrently for a `single` definition. Failed in repetition $repetition of the test.",
1,
numberOfInstances,
)
}
}

private fun createComponent(): Simple.ComponentA {
Thread.sleep(1) // Simulates a more expensive instance creation
return Simple.ComponentA()
}
}