simon.vergauwen
04/26/2019, 7:52 AMjava.util.concurrent.ThreadPoolExecutor
with a keepAlive of 0, will it respect that keepAlive
as a CoroutineContext
?Vsevolod Tolstopyatov [JB]
04/26/2019, 8:38 AMyourExecutor.asCoroutineDispatcher
?simon.vergauwen
04/26/2019, 8:39 AMclass CountingThreadFactory(val name: String) : ThreadFactory {
private val counter = AtomicInteger()
override fun newThread(r: Runnable): Thread =
Thread(r, "$name-${counter.getAndIncrement()}")
}
// Creates a ExecutorService that uses every thread only once, so every task is scheduled on a differently numbered Thread.
fun newTestingScheduler(name: String): ExecutorService =
ThreadPoolExecutor(0, 2, 0, TimeUnit.MILLISECONDS, SynchronousQueue<Runnable>(), CountingThreadFactory(name))
newTestingScheduler("test").asCoroutineDispatcher()
simon.vergauwen
04/26/2019, 8:40 AMVsevolod Tolstopyatov [JB]
04/26/2019, 8:51 AMasCoroutineDispatcher
respects keepAlive
.
Alternative is a mechanism of locks to test if functions get executed in parallel
keepAlive
is a racy mechanism for that.
E.g. you can have a function that supposed to launch two coroutines (and you want to test they are executed in parallel).
What could happen: the first coroutine is launched and executed, the caller is preempted by the OS. The first coroutine finishes its execution, the same time the caller launches the second coroutine and it is immediately taken by the first thread.
In the end, your counter
is still equal to one, though your code is completely correct.Vsevolod Tolstopyatov [JB]
04/26/2019, 8:56 AMsimon.vergauwen
04/26/2019, 8:58 AM