Thread end listener. Java

Denis picture Denis · Mar 2, 2011 · Viewed 21.1k times · Source

Are there any Listeners in Java to handle that some thread have been ended? Something like this:

Future<String> test = workerPool.submit(new TestCalalble());
test.addActionListener(new ActionListener()               
   {                                                         
    public void actionEnd(ActionEvent e)               
    {                                                        
        txt1.setText("Button1 clicked");                        
    }                                                        
   });

I know, that it is impossible to deal like this, but I want to be notified when some thread ended.

Usually I used for this Timer class with checking state of each Future. but it is not pretty way. Thanks

Answer

nanda picture nanda · Mar 2, 2011

There is CompletionService you can use.

CompletionService<Result> ecs
       = new ExecutorCompletionService<Result>(e);
ecs.submit(new TestCallable());
if (ecs.take().get() != null) {
    // on finish
}

Another alternative is to use ListenableFuture from Guava.

Code example:

ListenableFuture future = Futures.makeListenable(test);
future.addListener(new Runnable() {
 public void run() {
   System.out.println("Operation Complete.");
   try {
     System.out.println("Result: " + future.get());
   } catch (Exception e) {
     System.out.println("Error: " + e.message());
   }
 }
}, exec);

Personally, I like Guava solution better.