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
?
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.
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.
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.
Is there any particular advantage in decoupling the
get
method from theFuture
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With