kotlin concurrency revisited
I wrote a while ago about the nice concurrency features in kotlin. And as with all things there are some things that shine less when you get to use it for a while. I became a bit suspocious when I browsed the logs for a place where we do concurrenct calls. They seemed to coming on one after the other anyway and not all at the same time as expected. So I started to investigate and it turns out that kotlin concurrency out of the box only runs on one thread and will not be very concurrenct in the way you may expect. But fear not - there are ways to work around it.
When you start a concurrecnt block it is possible to pass in a CoroutineContext parameter to specify in what manner you would want the parallelism to proceed. To get a new single thread context you can pass in newSingleThreadContext("Name of a thread")
. Ot you can create your own Dispatcher to actually pass things on between the threads. If you are on a thread local centric framework like Spring this may be necessary in order to pass on security context, logging context and similar. So in order to get things running in parallel you need to read up on these things and implement them.
written by fredrik at 2025-01-27
More content on code
More content on kotlin
More content on programming
More content on concurrency