Custom Thread Pool with Coroutine async construct

Viewed 1066

I am using async construct to execute certain task in parallel.

ids.forEach { id -> val result = async { getResult(id) } }

I have 2 questions in this regard.

  1. I believe default thread pool to execute these tasks in parallel would have max(1, CPUs -1) threads. Is this understanding correct?
  2. I want to use custom thread pool instead.
val context = newFixedThreadPoolContext(15, "custom pool")

How can I pass this pool to the async construct. Please advice.

1 Answers

By default async() inherits a coroutine dispatcher from the context that invoked it. If you create a single threaded context and inside it call async() then it will run in the same single-threaded environment.

In some cases dispatcher may be unspecified, e.g. if you use GlobalScope.async(). In that case Dispatchers.Default is used. Documentation says that:

By default, the maximum number of threads used by this dispatcher is equal to the number of CPU cores, but is at least two.

Using async() with your own dispatcher is as simple as:

async(context) { getResult(id) }
Related