Driven Future Event <V> - Message Pool
We use callable<V>
and Future<V>
to get the result of the completed thread from the thread pool. We must call get()
to get the return result. My problem is that this is not an event. Is there any structure to get the result, for example, SIGCHLD
for child processes in C? I want something like this: (the thread pool will call this function when each thread in the pool has completed the task)
public void fetchResult(Thread t, Runnable r, Future<Integer> result) { Integer x = result.get(); /* handle x */ /* also we have Thread and Runnable object that has terminated */ }
you can check the ThreadPoolExecutor.afterExecute () method. it is called after the completion of each task. you can create a custom subclass of ThreadPoolExecutor that will have an event-based callback behavior.
You can easily create an event driven template. The following pseudo code illustrates one approach.
abstract class EventTemplate<T> implements Runnable { private BlockingQueue<T> queue; public void submit(Callable<T> callable) { queue.add(callable); } public abstract void handleEvent(T t); public void run() { for(;;) handleEvent(queue.take()); } public void start() { new Thread(this).start(); } }
Classes can extend the template.
class FooEventHandler extends EventTemplate<Foo> { public void handleEvent(Foo foo) { // do something } }
which can be created
new FooEventHandler().start();