简体   繁体   中英

Kotlin runBlocking and async with return

I am taking my first steps in kotlin coroutines and I have a problem.

In order to create Foo and return it from a function I need to call two heavy service methods asynchronously to get some values for Foo creating. This is my code:

   return runBlocking {
        val xAsync = async {
            service.calculateX()
        }
        val yAsync = async {
            service.calculateY()
        }
        Foo(xAsync.await(), yAsync.await())
    };

However, after reading logs is seems to me that calculateX() and calculateY() are called synchronously. Is my code correct?

Your code isn't perfect, but it is correct in terms of making calculateX() and calculateY() run concurrently. However, since it launches this concurrent work on the runBlocking dispatcher which is single-threaded, and since your heavyweight operations are blocking instead of suspending, they will not be parallelized.

The first observation to make is that blocking operations cannot gain anything from coroutines compared to the old-school approach with Java executors, apart from a bit simpler API.

The second observation is that you can at least make them run in parallel, each blocking its own thread, by using the IO dispatcher:

return runBlocking {
    val xAsync = async(Dispatchers.IO) {
        service.calculateX()
    }
    val yAsync = async(Dispatchers.IO) {
        service.calculateY()
    }
    Foo(xAsync.await(), yAsync.await())
};

Compared to using the java.util.concurrent APIs, here you benefit from the library's IO dispatcher instead of having to create your own thread pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM