4

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 */
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Majid Azimi
  • 5,575
  • 13
  • 64
  • 113
  • 1
    Can you please express it more? It is still not clear what you exactly want – Jatin Oct 23 '11 at 18:01
  • 1
    What part of "event-driven" is important to you? I'm assuming that it is not the lack of busy-waiting, since Future.get() doesn't busy-wait. – Avi Oct 23 '11 at 20:07
  • @Avi: It doesn't busy-wait but it locks. I don't want to lock. I want main thread do some job. when a thread from pool terminates the pool calls a function and in that function when I call `Future.get()` it returns immediately. – Majid Azimi Oct 24 '11 at 18:19

2 Answers2

1

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.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
0

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();
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148