Hacker News new | ask | show | jobs
by noelwelsh 4906 days ago
Scala's futures are wonderful to use. There are two main benefits:

1. They compose, meaning you can construct a Future out of other Futures

2. They work with Scala's for comprehension syntax making them very concise to use.

We use them everywhere in Myna. The one downside with plain futures is it's very easy to forget to handle errors, so we typically have a Future of a Validation. In Scala 2.10 you'd probably use Try in preference. I talk more about futures and our error handling strategy here: http://noelwelsh.com/blueeyes/concurrency.html

Finally, if you use Node.js and think callbacks are the cat's pyjamas you really should check out a futures implementation (not necessarily in Scala). They are a much better abstraction.

2 comments

While the Future abstraction in Scala is very nice, it is unfortunately not very good in a multi-threaded context. The implementation of Futures contains a lock that, IIRC, locks the outermost object they are contained in. For us, this led to lots of serialization of code that should and could run in parallel. We've unforunately had to remove all our use of Futures until the implementation matches the expected behaviour.
TIL. I was under the impression that they all ran (more or less) in parellel.
Depends on where and how they are created, but in our case lots of heavy futures were created in the same object. YMMV.
How about onFailure?
Let me expand: there is nothing in the type system that will make you handle exceptions in Futures, in the way that Option or Either make you handle the failure case. It is easy for a Future to fail and you to never see a stack trace. E.g. this will silently fail:

  Future { 1 / 0 }
An alternative is to encode the possibility of failure in the type system by using Future[Validation[E,A]] (replace Validation with Try or Either as the whim takes you). Then the type system will remind you to handle the failure case. See my link above for more (scroll down a bit to see the section on error handling).
I focussed on a example with a happy flow. In Akka Futures you can handle only error conditions of the following type.

for example we have future onSuccess future onFailure

or we have onComplete, future onComplete { case Success(result) ⇒ doSomethingOnSuccess(result) case Failure(failure) ⇒ doSomethingOnFailure(failure) }

else you can follow what is mentioned by noelwalsh