Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring boot kotlin coroutines doesn't run in parallel

I’m building a backend app with spring boot and kotlin. I wanna implement a parallel execution for a specific method. I tried to use coroutines but the underlaying method runs synchronously.

This is what I’ve tried so far:

fun getXsByIds(xIds: List<String>): List<X> {
        val xList = ArrayList<X>();
        runBlocking {
            val promises = xIds.map {
                async {
                    getXById(it)
                }
            };
            
            xList.addAll((promises.awaitAll()).filterNotNull())
        }
        return xList;
    }

    fun getXById(xId: String): X? {
        // This method makes request to database
    }

When I put logs in getXById method like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fun getXById(xId: String): X? {
        print("start");
        // This method makes request to database
        print("end");
    }

I get this output

start
end
start
end
start
end
...

Why is my coroutines not working in parallel? This is in spring boot. Not reactive. Thread per request style.

>Solution :

Calling async without specifying any coroutine elements means it will inherit them all (bar the job) from its parent. This causes your "async" call to execute on runBlockings blocking dispatcher.

Try using async(Dispatchers.Default) { ... } instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading