Search code examples
spring-bootkotlinkotlin-coroutines

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

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.