user3248346
user3248346

Reputation:

What are the differences between a Scala Future and a Java Future

Are there any conceptual, functional or mechanical differences between a Scala Future and a Java Future? Conceptually I can't see any differences as they both aim to provide a mechanism for asynchronous computation.

Upvotes: 23

Views: 9220

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

The main inconvenience of java.util.concurrent.Future is the fact that you can't get the value without blocking.

In fact, the only way to retrieve a value is the get method, that (quoting from the docs)

Waits if necessary for the computation to complete, and then retrieves its result.

With scala.concurrent.Future you get instead a real non-blocking computation, as you can attach callbacks for completion (success/failure) or simply map over it and chain multiple Futures together in a monadic fashion.

Long story short, scala's Future allows for asynchronous computation without blocking more threads than necessary.

Upvotes: 42

sekhar
sekhar

Reputation: 700

Java Future:Both represent result of an Asynchronous computation,but Java's Future requires that you access the result via a blocking get method.Although you can call isDone to find out if a Java Future has completed before calling get, thereby avoiding any blocking, you must wait until the Java Future has completed before proceeding with any computation that uses the result.

Scala Future: You can specify transformations on a Scala Future whether it has completed or not.Each transformation results in a new Future representing the asynchronous result of the original Future transformed by the function. This allows you to describe asynchronous computations as a series of transformations.

Scala's Future often eliminate, the need to reason about shared data and locks.When you invoke a Scala method, it performs a computation "while you wait" and returns a result. If that result is a Future, the Future represents another computation to be performed asynchronously often by a completely different thread.

Example: Instead of blocking then continuing with another computation, you can just map the next computation onto the future.

Following future will complete after ten seconds:

val fut = Future { Thread.sleep(10000);21+21}

Mapping this future with a function that increments by one will yield another future.

 val result = fut.map(x=>x+1)

Upvotes: 4

Related Questions