How to Create Controllable Futures in Scala
In this article, we discuss how to create controllable Futures in Scala with the help of Promises.
Join the DZone community and get the full member experience.Join For Free
You know the value inside will be evaluated on "some" thread, at "some" point in time, without your control.
with the assumption that you're issuing a request to some multi-threaded service which, is getting called all the time. Let's also assume that the service looks like this:
The service has two API methods:
A "production" function that is completely deterministic.
A submission function that has a pretty terrible API because the function argument will be evaluated on one of the service's threads, and you can't get the returned value back from another thread's call stack.
because spawning up the thread responsible for evaluating the production function is not up to you.
Then pass that promise to someone else, perhaps an asynchronous service:
And at the moment, the promise contains a value. Its future will automatically be fulfilled with that value, which will unlock the consumer.
How to Use it
We create a promise and then we return its future at the end for whoever wants to consume it. In the middle, we submit a function that will be evaluated at some point out of our control. At that moment, the service produces the value and fulfills the Promise, which will automatically fulfill the Future for the consumer.
Published at DZone with permission of Daniel Ciocirlan. See the original article here.
Opinions expressed by DZone contributors are their own.