Future goodies and helpers: SafeFuture, TimeoutFuture, CancelableFuture
Related to our previous post about catching top-level Actor exceptions, we also have a few utility classes for working with Futures. These do things such as offer baked-in exception logging, establish SLA-timeouts on futures, and give the ability to interrupt a running code block that is in a future.
Check out all of the code together on
SafeFuture
SafeFuture is a Future that simply binds an onFailure to any future passed in to deal with hard failures. Future failures can and should be handled, but for fire-and-forget and map-chaining, it’s often easy to not handle failures explicitly. The result is a exception that goes nowhere — including failure to your go to your logs. Mysterious failure is not good, so SafeFuture lets you design an application level failure monitoring strategy. This won’t save your result, but at least you’ll be aware it failed.
As an added bonus, there’s a second apply in SafeFuture that lets you name the future for logging purposes.
TimeoutFuture
TimeoutFuture lets you establish a SLA timeout for a Future. Simply, if that time passes and the future has not resolved, it resolves as a failure with a TimeoutException. Typically, this should be explicitly handled by your application — supplying a default value, returning an error, etc.
For efficiency, we use netty’s HashWheelTimer. This does not give explicit guarantees about exactly when it runs, and instead provides a best-effort timer. So: It’s much lighter than a scheduler, but less accurate.
CancelableFuture
CancelableFuture creates a future that can be cancelled, from a blocking code block. This is not usually for SLA timeout guarantees like above. Rather, it’s for when you have a complex long-running blocking bit of code that you want to be able to kill. So, this returns a method that, once called, will harshly interrupt the thread and stop the code. It’s nasty, be careful with it. Example non-deterministic usage:
All of this code together (with necessary imports) is on Github. Have any other useful utility classes for working with Akka and Futures? Let us know!
We wrote this post while working on Kifi — tools that help people outsmart information overload together. Learn more.
Originally published at eng.kifi.com on August 28, 2013.