-
-
Notifications
You must be signed in to change notification settings - Fork 711
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #914 from Sloy/single-concurrency
Fix concurrency issue for Single definitions
- Loading branch information
Showing
2 changed files
with
50 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 43 additions & 0 deletions
43
koin-projects/koin-core/src/test/java/org/koin/core/SingleConcurrencyTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} |