# coroutines

Marcin Wisniowski

07/05/2020, 10:06 PM
I'm building a massively concurrent system with coroutines, have thousands of coroutines running at a time, and have 100% CPU usage most of the time. It all works great, but how can I give some coroutines higher priority? Sometimes I have work incoming that should be completed first, but because the application is already busy with other stuff the priority work has to wait for other work to finish before being processed. Alternatively, how can I start some coroutines on a low-priority thread, which should let me achieve the same goal?


07/05/2020, 10:08 PM
make your own dispatcher using

Marcin Wisniowski

07/05/2020, 10:19 PM
Oh, that makes sense, I was looking at CoroutineDispatchers but haven't seen that you can make one from an Executor. Thank you.


07/11/2020, 7:16 PM
If your only using 1 thread currently ( what I interpreted as 100% cpu and massive coroutine use) - then you dont need your own dispatcher you can just use the Default instead of Main dispatcher -- depends on what your currently useing and/or newSingleThreadContext or newFixedThreadPoolContext Or create your own thread pool and executor and manually or dynamically assign thread priorities. For your case you probably don't need to write a full dispatcher.

Marcin Wisniowski

07/12/2020, 10:18 AM
Copy code
fun createCoroutineDispatcher(priority: Int): CoroutineDispatcher {
    return Executors.newCachedThreadPool(ThreadFactory {
        return@ThreadFactory Thread(it).apply {
            this.priority = priority
I created a dispatcher like this, allowing me to set priority. Seems to work. @DALDEI