SCALA FUTURES AND PROMISES

  • date 18th February, 2021 |
  • by Prwatech |
  • 0 Comments

Futures

A future is an object holding a value that may become available at some point. This value is usually the result of some other computation:

If the computation has not yet completed, we say that the Future is not completed.
If the computation has completed with a value or with an exception, we say that the Future is completed.
Completion can take one of two forms:

When a future is completed with a value, we say that the future was successfully completed with that value.
When a Future is completed with an exception thrown by the computation, we say that the Future was failed with that exception.
A Future has an important property that it may only be assigned once. A Future object is given a value or an exception, it becomes in effect immutable, it can never be overwritten.

Promises

So far we have only considered Future objects created by asynchronous computations started using the Future method. However, futures can also be created using promises.

While futures are defined as a type of read-only placeholder object created for a result that doesn’t yet exist, a promise can be thought of as a writable, single-assignment container, which completes a future. That is, a promise can be used to successfully complete a future with a value by completing the promise using the success method, a promise can also be used to complete a future with an exception by failing the promise, using the failure method.

A promise p completes the future returned by p. This future is specific to the promise p. Depending on the implementation, it may be the case that p. future eq p.

Consider the following producer-consumer example, in which one computation produces a value and hands it off to another computation that consumes that value. This passing of the value is done using a promise.

Quick Support

image image