在Scala中如何让线程等待未来的结果准备好?

时间:2022-01-10 22:05:18

I have a callback handler which handles one of many phases of a URL processing. In this handler I have to use a third party library (scala interface)and compute some value which will set one global configuration. This configuration is used by followings phase and value it gets in callback handler plays a critical role.

我有一个回调处理程序,它处理URL处理的许多阶段之一。在这个处理程序中,我必须使用第三方库(scala接口)并计算一些值,这将设置一个全局配置。此配置由以下阶段使用,它在回调处理程序中获得的值起着至关重要的作用。

Here is how design looks

这是设计的外观

def callbackHandler() : someReturnType = {
    val myFut = getMyData() // return a future
    myFut map {m => set_global} // evaluate the future
    someReturnTypeObject
}

With this context, here is my question. Scala API I am using returns a future to me, and I evaluate it using "map". As I understand after getting future instance, callback function will move on with pending stuff and future will be evaluated when it is available(in a separate thread).

有了这个背景,这是我的问题。我正在使用的Scala API向我返回一个未来,我使用“map”来评估它。正如我在获得未来实例后所理解的那样,回调函数将继续使用待处理的东西,并且将在可用时评估将来(在单独的线程中)。

In such scenario how I will make sure to keep callback handler waiting for future evaluation?

在这种情况下,我将如何确保让回调处理程序等待将来的评估?

moving line 4 to map body may not work, as callbackhandler may still return early if map is taking time.Please let me know if you have some question, or if I am wrong in my understanding.

移动第4行到地图主体可能无法正常工作,因为如果地图需要时间,回调处理程序仍可能提前返回。如果您有疑问,请告诉我,或者如果我的理解错误,请告诉我。

1 个解决方案

#1


The purpose of using a Future is to not block a thread. Ideally you should execute the code you want as part of the completion of the future, rather than blocking the future and resume on the same thread.

使用Future的目的是不阻塞线程。理想情况下,您应该在未来完成时执行您想要的代码,而不是阻止未来并在同一个线程上继续。

That said, the mechanism for blocking on a future is:

也就是说,阻止未来的机制是:

val result = Await.result(myFut, 10.seconds)

where 10.seconds is the longest you are willing to wait.

其中10.seconds是你愿意等待的最长时间。

You should also note that map does not evaluate the future. The evaluation starts as soon as you call getMyData. All that map does is transform the result of the future into a future, once that result is available.

您还应该注意,地图不会评估未来。一旦调用getMyData,评估就会开始。一旦该结果可用,所有该地图所做的就是将未来的结果转化为未来。

#1


The purpose of using a Future is to not block a thread. Ideally you should execute the code you want as part of the completion of the future, rather than blocking the future and resume on the same thread.

使用Future的目的是不阻塞线程。理想情况下,您应该在未来完成时执行您想要的代码,而不是阻止未来并在同一个线程上继续。

That said, the mechanism for blocking on a future is:

也就是说,阻止未来的机制是:

val result = Await.result(myFut, 10.seconds)

where 10.seconds is the longest you are willing to wait.

其中10.seconds是你愿意等待的最长时间。

You should also note that map does not evaluate the future. The evaluation starts as soon as you call getMyData. All that map does is transform the result of the future into a future, once that result is available.

您还应该注意,地图不会评估未来。一旦调用getMyData,评估就会开始。一旦该结果可用,所有该地图所做的就是将未来的结果转化为未来。