简体   繁体   English

Kotlin runBlocking 和 async with return

[英]Kotlin runBlocking and async with return

I am taking my first steps in kotlin coroutines and I have a problem.我正在 kotlin 协程中迈出第一步,但遇到了问题。

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.为了创建Foo并从函数中返回它,我需要异步调用两个繁重的服务方法来获取一些用于Foo创建的值。 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.但是,在我看来,在阅读日志之后, calculateX()calculateY()是同步调用的。 Is my code correct?我的代码正确吗?

Your code isn't perfect, but it is correct in terms of making calculateX() and calculateY() run concurrently.您的代码并不完美,但在使calculateX()calculateY()同时运行方面是正确的。 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.但是,由于它在runBlocking调度程序上启动此并发工作,并且由于您的重量级操作是阻塞而不是挂起,因此它们不会被并行化。

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.首先要观察的是,与使用 Java 执行程序的老派方法相比,阻塞操作无法从协程中获得任何好处,除了更简单的 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:第二个观察结果是,您至少可以通过使用 IO 调度程序使它们并行运行,每个都阻塞自己的线程:

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.与使用java.util.concurrent API 相比,在这里您可以从库的 IO 调度程序中受益,而不必创建自己的线程池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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