Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for any of given Futures in Scala?

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?

like image 865
Michael Avatar asked Apr 11 '13 13:04

Michael


People also ask

What is future in Scala?

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

How to write parallel/concurrent applications in Scala?

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:

How to mark methods to run asynchronously in Scala?

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.

How to use the fallbackto() method in Scala?

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.


1 Answers

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.

like image 168
om-nom-nom Avatar answered Nov 12 '22 19:11

om-nom-nom