Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 351
M.K. Avatar asked Jul 12 '15 09:07

M.K.


People also ask

What is a Scala Future?

Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.

What are Futures in Java?

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

What is a promise and Future Scala?

Promise. The Promise is a writable, single-assignment container that completes a Future. The Promise is similar to the Future. However, the Future is about the read-side of an asynchronous operation, while the Promise is about the write-side.

Is Scala Future a Monad?

yes, then it's a monad. @ElectricCoffee no. @PabloFernandez Scala's flatMap is Haskell's >>= , and Scala's for-comprehensions are equivalent to Haskell's do notation.


1 Answers

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.

like image 143
Gabriele Petronella Avatar answered Oct 02 '22 03:10

Gabriele Petronella