The introduction of CompletableFutures
in Java 8 brought to the language features available in the scala.concurrent.Future
such as monadic transformations.
What are the differences, and why a Scala developer should prefer Scala Futures over java 8 CompletableFuture
?
Are there still good reasons to use the scala.concurrent.Future
in Java through akka.dispatch
bridge?
Future vs CompletableFuture. CompletableFuture is an extension to Java's Future API which was introduced in Java 5. A Future is used as a reference to the result of an asynchronous computation.
A Java Future works in a synchronous blocking way. It does not work in an asynchronous non-blocking way, whereas a Scala Future works in an asynchronous non-blocking way. If we want an asynchronous non-blocking feature, we should use Java 8's CompletableFuture.
A CompletableFuture is an extension to Java's Future API which was introduced in Java 8. A Future is used for asynchronous Programming. It provides two methods, isDone() and get(). The methods retrieve the result of the computation when it completes.
CompletableFuture allows us to write non-blocking code by running a task on a separate thread than the main application thread and notifying the main thread about its Progress, Completion or Failure. CompletableFuture is inspired from ListenableFuture in Guava and Are similar to Promise in java scripts.
What are the differences, and why a Scala developer should prefer Scala Futures over java 8 CompletableFuture ?
Rephrasing what @dk14 pointed out in comments I'd say that CompletableFuture
doesn't have idiomatic Scala api.
For scala developer the implications are:
It is also worth noting that java CompletableFuture
is not exactly equivalent of scala Future
. It is rather a fuse of scala Future
and Promise
.
Considering the cons listed above there isn't much sense in using CompletableFuture
in scala unless you are designing public api that should be seamlessly interoperable with java.
Are there still good reasons to use the scala.concurrent.Future in Java through akka.dispatch bridge?
I am particularly looking for reasons to use akka.dispatch in Java, if there are still any
Akka is build on top of scala and it sometimes uses scala Future
s. This means that in cases when you have some portion of code written in java it is worth to wrap it in scala api (with akka.dispatch
java api) to be able to easily use it with akka.
For example, you are implementing akka actor in java. When processing message you want to do some non-blocking reading that, when done, should produce result as a message to another actor.
What you could do is to put your I/O into java Callable, then use akka.dispatch.Futures#future to get scala Future
out of it, and then you could leverage akka pipe to make result of the future be delivered as a message to some actor.
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