If I have `class Foo { suspend fun execute(): Bar ...
# coroutines
d
If I have
class Foo { suspend fun execute(): Bar }
and I want to limit that
execute
should not run in parallel is the simplest way (without channels) to use
newSingleThreadContext
to create one thread context in the class and use it in
withContext(executeContext)
in
execute
? Is there anything wrong with this, or a better way?
d
I don't know if this is better but for something like that I'd use a
Mutex
. https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/
d
I need it to run off the main thread anyways, so the context switching is inevitable, but I use Mutex for another similar case that doesn't require context switching.
d
So you're not using an existing dispatcher then?
d
The existing dispatchers are pools, so if a thread is free, it will run the next
execute
in parallel AFAIK, which is not what I want. By limiting to one thread, it'll block until I return the first result. I could call this from many threads and it should still be FIFO.
d
By limiting to one thread you do get implicit synchronization. I was thinking you could still re-use the existing dispatchers' threads, if you use explicit synchronization(
Mutex
).
d
Any advantage to that?
d
You don't create another thread?
If your function is possibly called from an existing dispatcher, there might be no thread switching.
d
It's just a temporary one, the question is how much overhead will that involve compared to
Mutex
?
there might be no thread switching
Mutex
is less overhead than that switching I'm saving?
d
I reckon it is less overhead but I don't know.
d
I guess it's worth a try, thanks 🙂.