vikrant
vikrant

Reputation: 433

In Scala how to make a thread wait for a future results to be ready?

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.

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).

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.

Upvotes: 0

Views: 851

Answers (1)

Arne Claassen
Arne Claassen

Reputation: 14404

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.

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.

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.

Upvotes: 1

Related Questions