I feel like I might be missing something here, but...
# coroutines
e
I feel like I might be missing something here, but why does the JVM implementation of
newFixedThreadPoolContext
use
Executors.newScheduledThreadPool
(which is bounded by
nThreads..Int.MAX_VALUE
) instead of
Executors.newFixedThreadPool
(which is bounded by
nThreads..nThreads
)?
I guess it needs to be a
ScheduledThreadPoolExecutor
? Then either specify the
maximumPoolSize
or change the name (or at least mention it in the docs)?
d
Sorry, I don't understand the question. What's the problem? Do you believe the thread pool created by
newFixedThreadPoolContext(n)
can contain more than
n
threads? A simple experiment doesn't show this: https://pl.kotl.in/QmqJMp0Da Could you describe a specific problematic scenario?
e
My question is why doesn't it contain more than
n
threads?
d
That's what the function is intended to do. From https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/new-fixed-thread-pool-context.html :
Creates a coroutine execution context with the fixed-size thread-pool
n
is the fixed size.
e
I know that, but looking at the JVM implementation it uses
Executors.newScheduledThreadPool
and doesn't set an upper bound
d
Ok, and what's the problem with that?
e
No problem, I'm just curious about how it doesn't create more than
n
threads when the executor isn't preventing it
d
Here's essentially what happens in the example above: https://pl.kotl.in/uEfczVAUy So, the executor is preventing it.
e
Right, so that results in
ThreadPoolExecutor
getting called with
corePoolSize=4
and
maximumPoolSize=Int.MAX_VALUE
. The javadoc for those says:
corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize – the maximum number of threads to allow in the pool
which sounds like it will always keep at least 4 threads, but can grow to
Int.MAX_VALUE
threads.
d
Here's an example of how it would be possible to create extra threads, sidestepping the set bound: https://github.com/Kotlin/kotlinx.coroutines/pull/4364/files If we merge the PR, even that won't be possible, though.
e
This is what I was looking for:
Using a custom queue (DelayedWorkQueue), a variant of unbounded DelayQueue.
Since it used an unbounded queue, it shouldn't create more than
n
threads.