Reputation: 5745
We use callable<V>
and Future<V>
to receive the result of a terminated thread from a thread pool. We should call get()
to receive the returned result. My problem is: it is not event driven. Is there any framework to get result like SIGCHLD
for child processes in C?
I want something like this:(the thread pool will call this function when each thread in the pool finished the job)
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 */
}
Upvotes: 4
Views: 1513
Reputation: 53694
you might want to check out the ThreadPoolExecutor.afterExecute() method. it's called after each task completes. you could create a custom subclass of ThreadPoolExecutor which has the event based callback behavior you desire.
Upvotes: 1
Reputation: 49187
You could 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 the extend the template
class FooEventHandler extends EventTemplate<Foo> {
public void handleEvent(Foo foo) {
// do something
}
}
Which can be instantiated
new FooEventHandler().start();
Upvotes: 0