Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to Java thread after a join call with timeout

What state is a Java thread in after you call join with a timeout value, and the timeout passes. So for instance you have the following code:

Thread thread = new Thread();
thread.start();
thread.join(TIMEOUT);

and the timeout passes and the thread hasn't returned what is the state? What do I need to be aware of to make sure I don't leak threads. My initial assumption is that after the join call doing something like:

if (thread.isAlive())
{
   thread.interrupt();
   thread = null;
}

To check if the thread is still running and if so interrupt it, and then null it out to make sure it gets garbage collected.

like image 550
Patrick McDaniel Avatar asked Apr 14 '11 01:04

Patrick McDaniel


1 Answers

The Javadoc states that the join(time) function will wait at most that many milliseconds for the thread to die. In effect if the timeout passes your code will stop blocking and continue on. If you are worried about 'leaking threads' in this case you probably should redesign so that you don't have to join the thread and can observe the state of the running thread. Furthermore calling an interrupt on the thread is bad mojo.

class MyThread extends Thread {
    private boolean keepRunning = true;
    private String currentStatus = "Not Running";
    public void run() {
        currentStatus = "Executing"
        while(keepRunning)
        {
           try {
               someTask()
               currentStatus = "Done";
           } catch (Exception e) {
               currentStatus = "task failed";
               keepRunning = false;
           }
        }
    }

    public stopThread() {
       keepRunning = false;
    }
}

Above might be a better example to work off of to work with threads. You need not set the thread to null explicitly, but for example if you're storing threads in an ArrayList remove it from the list and let Java handle it.

like image 63
Vetsin Avatar answered Oct 15 '22 10:10

Vetsin