Suppose I need to execute a few parallel tasks in Scala. Each task performs some blocking call (e.g. Process.waitFor
). Now I would like to wait until any of the tasks completes.
As I understand I should use Scala Future
to wrap the task. Is there any API in Scala to wait until any of given Futures
finishes?
Some operations like a database query or a call to another HTTP service can take a while to complete. Running them on the main thread would block further program execution and decrease performance. In this tutorial, we’ll focus on Future, which is a Scala approach to running operations in the background and a solution to this problem. 2. Future
When you want to write parallel and concurrent applications in Scala, you could still use the native Java Thread — but the Scala Future makes parallel/concurrent programming much simpler, and it’s preferred. Here’s a description of Future from its Scaladoc:
So far we've been using future's return type to mark our methods to run asynchronously. Scala provides an abstraction over future and it is called a Promise. Promises can be useful when you want to capture the intent of your operation versus its behaviour. 1. Define a method which returns a Future As usual, we start with our donutStock () method.
As mentioned in the official Scala API documentation on futures, Scala also provides a fallbackTo () method which allows you to provide an alternative method that can be called in the event of an exception. 1. Define a method which returns a Future As usual, we start by defining our donutStock () method which returns a Future of type Int.
There is build-in method for doing this:
Future.firstCompletedOf(yourFutures)
from the doc:
Returns a Future to the result of the first future in the list that is completed.
Note that this would not interrupt all other futures so you have cancel them by yourself, if you need to.
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