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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With