Meaningless Drivel is fun!*
The moose likes Threads and Synchronization and the fly likes Implementing task result listener in executor framework Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Implementing task result listener in executor framework" Watch "Implementing task result listener in executor framework" New topic

Implementing task result listener in executor framework

Pavel Kazlou
Ranch Hand

Joined: Sep 07, 2009
Posts: 33
Everyone praises Executor framework (that one in java.util.concurrent). But I'm stucked with such a problem.
I want to execute different tasks in thread pool and don't want to wait for their results in get method of Future interface. I just want some things to be done immediately after the execution completes (either with return or with exception). The only thing I was able to find to implement such listening for task completion is protected method of ThreadPoolExecutor class - afterExecute. This brings two unpleasant things: extending executor and messing with afterExecute parameters (Runnable, Throwable).
I wonder why the creators of Executor framework couldn't just provide the setter for listener interface in order to pass him the results (something like Future) upon task completion? Am I missing something? Why choosing between synchronous get and unhandy afterExecute?

Can you advise any technique to solve my problem? It seems to be so trivial, just returning results upon completion. That is why I can't believe the framework is not suitable for such scenario.

P.S. I use java 5.
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
You may extend the FutureTask class and imlement your own done() method.
This method is called just after the task is completed.

Maybe like this:
Pavel Kazlou
Ranch Hand

Joined: Sep 07, 2009
Posts: 33
Thank you, Ireneusz! I can't believe this happens to me!
Strange things a have found only one example of using done() while googling. The other examples are plain get() calling. Why does everybody like hanging thread while waiting for result?
Nevertheless I've just successfully implemented my scenario. I extended FutureTask class in such a way:

Everything is easy and understandable now. So, thank you again, Ireneusz!
I agree. Here's the link:
subject: Implementing task result listener in executor framework
Similar Threads
Number of working threads using java executor framework
stopping a runnable in ThreadPoolExecutor
Limit concurrent threads; report successful execution; terminating hung threads
How to add actionListener to ScheduledExecutorService?
ExecutorService invokeAll - blocking?