https://kotlinlang.org logo
Title
r

ribesg

01/18/2023, 2:34 PM
How do you do atomic values in common code? atomicfu seems broken, this test does not pass
@Test
    fun test() {
        val threadPool = newFixedThreadPoolContext(8, "TestDispatcher")
        val scope = CoroutineScope(threadPool)
        val atomic = atomic(0L)
        repeat(100_000) {
            scope.launch {
                atomic.incrementAndGet()
            }
        }
        assertEquals(100_000, atomic.value)
    }
Stately looks dead
j

jw

01/18/2023, 2:35 PM
you aren't waiting for the jobs to complete
r

ribesg

01/18/2023, 2:36 PM
Ah, tried to reduce a bigger use case into a test and failed miserably 😄
This works so I probably have a similar issue somewhere in the real code
@Test
    fun test() = runBlocking {
        val threadPool = newFixedThreadPoolContext(8, "TestDispatcher")
        val scope = CoroutineScope(threadPool)
        val atomic = atomic(0L)
        val jobs = (1..100_000).map {
            scope.launch {
                atomic.incrementAndGet()
            }
        }
        jobs.joinAll()
        assertEquals(100_000, atomic.value)
    }