Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread end listener. Java

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

like image 866
Denis Avatar asked Mar 02 '11 15:03

Denis


2 Answers

Here is a geekish listener. Highly unadvisible to use but, funny and clever

Thread t = ...
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        t.getThreadGroup().uncaughtException(t, e);//this is the default behaviour
    }       
    protected void finalize() throws Throwable{
        //cool, we go notified
      //handle the notification, but be worried, it's the finalizer thread w/ max priority
    }
});

The effect can be achived via PhantomRefernce better

hope you have a little smile :)


Side note: what you ask is NOT thread end, but task completion event and the best is overriding either decorateTask or afterExecute

like image 69
bestsss Avatar answered Sep 18 '22 12:09

bestsss


No. Such listener does not exist. But you have 2 solutions.

  1. Add code that notifies you that thread is done in the end of run() method
  2. Use Callable interface that returns result of type Future. You can ask Future what the status is and use blocked method get() to retrieve result
like image 24
AlexR Avatar answered Sep 21 '22 12:09

AlexR