Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Scala's Future have a .get / get(maxDuration) method, forcing us to resort to Await.result() instead?

Tags:

scala

future

Is there any particular advantage in decoupling the get method from the Future class (where I'd expect it to reside) and to instead force the coder to have to know about this external two-method class called Await?

like image 416
devoured elysium Avatar asked Jul 01 '16 23:07

devoured elysium


People also ask

How do you handle Future Scala?

Handle the result of a future with methods like onComplete , or combinator methods like map , flatMap , filter , andThen , etc. The value in a Future is always an instance of one of the Try types: Success or Failure.

What is await result in Scala?

Await. result tries to return the Future result as soon as possible and throws an exception if the Future fails with an exception while Await. ready returns the completed Future from which the result (Success or Failure) can safely be extracted.

What is Future and promise in Scala?

The Promise is a writable, single-assignment container that completes a Future. The Promise is similar to the Future. However, the Future is about the read-side of an asynchronous operation, while the Promise is about the write-side.


1 Answers

Is there any particular advantage in decoupling the get method from the Future class

Yes, to make it difficult for the developer to do the wrong thing. A Future represents a computation which will complete in the future and might not be available at the current invocation point. If you need to block a future, why not execute it synchronously? Whats the point of scheduling it on the threadpool, wasting a perfectly good threadpool thread?

The documentation says:

Blocking outside the Future

As mentioned earlier, blocking on a future is strongly discouraged for the sake of performance and for the prevention of deadlocks. Callbacks and combinators on futures are a preferred way to use their results. However, blocking may be necessary in certain situations and is supported by the Futures and Promises API.

And even the Await object documentation:

While occasionally useful, e.g. for testing, it is recommended that you avoid Await when possible in favor of callbacks and combinators like onComplete and use in for comprehensions. Await will block the thread on which it runs, and could cause performance and deadlock issues.

You can see that the language designers intentionally wanted this effect.

like image 116
Yuval Itzchakov Avatar answered Oct 04 '22 09:10

Yuval Itzchakov