293659 (4) [Avatar] Offline
#1
v5, chapter 3, p. 78 contains the somewhat incorrect statement that prior to Java 8, Java's futures required blocking to get the result of the computation out. However, the JDK offers FutureTask (since version 1.5), which has the protected method done(), which is invoked asynchronously upon completion of the task.

I really like the book.
roland.kuhn (39) [Avatar] Offline
#2
Thanks for the correction, although I must admit that I have never seen FutureTask being used in APIs. As such it does not seem to be relevant, but I could be missing something.
293659 (4) [Avatar] Offline
#3
FutureTask is an implementation of Future, which allows use of the result in further computations without the need to block. Therefore, it is misleading to say that without blocking you can’t get the result out of a pre Java 8 Future, when the JDK provides FutureTask, a Future, which supports this. I think the statement should be qualified accordingly.
roland.kuhn (39) [Avatar] Offline
#4
I don’t follow: given an API that returns a
java.util.concurrent.Future
, can you illustrate how you would make use of the
FutureTask.done()
method in practice?

Unless I am missing something you can neither cast to FutureTask (because Future is an interface that can and is implemented differently) nor can you inject code into the
done
method from the outside in order to get notified of completion. In order for this to be usable the API would have to accept a FutureTask instead of handing out a Future, but I know of no examples where this is actually the case.
roland.kuhn (39) [Avatar] Offline
#5
(BTW: this forum implementation sucks so badly it is not even funny—sorry for that!)
293659 (4) [Avatar] Offline
#6
What I had in mind is sub-classing FutureTask, similar to this:

class F<T> extends FutureTask<T> {

private Runnable action;

public F(Callable<T> callable) {
super(callable);
}

public void onDone(Runnable action) {
this.action = action;
}

@Override
protected void done() {
action.run();
}
}


roland.kuhn (39) [Avatar] Offline
#7
Yes, I understood that earlier, but how do you propose to actually make use of this subclass with existing APIs? From what I can see there is simply no ecosystem around FutureTask that supports this kind of usage, whereas CompletionStage and CompletableFuture are built such that this kind of usage comes naturally (and all the relevant combinators are already implemented—onDone is not very interesting apart from serving as plumbing for real combinators like map/flatMap/andThen/…).
293659 (4) [Avatar] Offline
#8
Agreed. I guess what I missed in the book is a sentence that all this is in terms of the ecosystem etc as you explained above.
roland.kuhn (39) [Avatar] Offline
#9
Right, note taken. Thanks for pointing this out!