If I have a `java.util.concurrent.ThreadPoolExecut...
# coroutines
s
If I have a
java.util.concurrent.ThreadPoolExecutor
with a keepAlive of 0, will it respect that
keepAlive
as a
CoroutineContext
?
v
do you mean
yourExecutor.asCoroutineDispatcher
?
s
Yes, below is the full snippet.
Copy code
class 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()
Alternative is a mechanism of locks to test if functions get executed in parallel. Other alternatives (or resources I could check out) would also be very appreciated! 🙂
v
Yes,
asCoroutineDispatcher
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.
👍 1
One of the options is to write stress tests (though they are still probabilistic). Another one is to use locks or a special dispatcher that keeps track of submitted coroutines in an application/test specific way
s
Alright, thanks for the info!