Last active
December 20, 2020 14:57
-
-
Save Malinskiy/8cbad94d8abce5dd90e37f0f4b932f5f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.malinskiy.marathon.execution.queue | |
import kotlinx.coroutines.async | |
import kotlinx.coroutines.cancelAndJoin | |
import kotlinx.coroutines.channels.Channel | |
import kotlinx.coroutines.channels.actor | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.newFixedThreadPoolContext | |
import kotlinx.coroutines.runBlocking | |
import org.junit.jupiter.api.Test | |
import java.util.concurrent.ThreadPoolExecutor | |
import kotlin.random.Random | |
class MysteryTest { | |
@Test | |
fun `test X`() { | |
runBlocking { | |
var i = 0 | |
while (true) { | |
println("trying ${i++}") | |
map["key"] = 0 | |
val src1 = newFixedThreadPoolContext(1, "src1") | |
val src2 = newFixedThreadPoolContext(1, "src2") | |
val actor = actor<Unit>( | |
capacity = Channel.UNLIMITED | |
) { | |
for (msg in channel) { | |
processRequest() | |
} | |
} | |
val producer1 = async(src1) { | |
while (!actor.isClosedForSend) { | |
delay(30) | |
println("gen src 1") | |
actor.send(Unit) | |
} | |
} | |
val producer2 = async(src2) { | |
while (!actor.isClosedForSend) { | |
delay(70) | |
println("gen src 2") | |
actor.send(Unit) | |
} | |
} | |
for(i in 1..30000) { | |
delay(1) | |
} | |
producer1.cancelAndJoin() | |
producer2.cancelAndJoin() | |
actor.close(null) | |
src1.close() | |
src2.close() | |
} | |
} | |
} | |
} | |
val map = mutableMapOf<String, Int>() | |
private suspend fun processRequest() { | |
check() | |
} | |
private suspend fun check() { | |
val i = map["key"] | |
when(i) { | |
0 -> increment() | |
1 -> decrement() | |
else -> throw RuntimeException("Mystery $i") | |
} | |
} | |
private suspend fun increment() { | |
delay(100) | |
map["key"] = map["key"]!! + 1 | |
println("increment") | |
} | |
private suspend fun decrement() { | |
delay(50) | |
map["key"] = map["key"]!! - 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment