Java Future has cancel
method, which can interrupt the thread, which runs the Future
task. For example, if I wrap an interruptible blocking call in a Java Future
I can interrupt it later.
Scala Future provides no cancel
method. Suppose I wrap an interruptible blocking call in a Scala Future
. How can I interrupt it?
I haven't tested this, but this expands on the answer of Pablo Francisco Pérez Hidalgo. Instead of blocking waiting for the java
Future
, we use an intermediatePromise
instead.By cancelling I guess you would like to violently interrupt the
future
.Found this segment of code: https://gist.github.com/viktorklang/5409467
Did a few tests and seems to work fine!
Enjoy :)
I think it is possible to reduce the complexity of the implementations provided by making use of the Java 7
Future
interface and its implementations.Cancellable
can build a Java future which is the one to be cancelled by itscancel
method. Another future can wait for its completion thus becoming the observable interface which is itself immutable in state:This is not yet a part of the
Future
s API, but may be added as an extension in the future.As a workaround, you could use the
firstCompletedOf
to wrap 2 futures - the future you want to cancel and a future that comes from a customPromise
. You could then cancel the thus created future by failing the promise:Now you can call this on any future to obtain a "cancellable wrapper". Example use-case:
EDIT:
For a detailed discussion on cancellation, see Chapter 4 in the Learning concurrent programming in Scala book.