I have Ant build and execute a java program. This program tries to do something that sometimes hangs, so we execute it in a thread.
actionThread.start();
try {
actionThread.join(10000);
} catch (InterruptedException e) {
System.out.println("InterruptedException: "+e.getMessage());
}
if (actionThread.isAlive()) {
actionThread.interrupt();
System.out.println("Thread timed out and never died");
}
The ant call looks like this:
<java fork="true" failonerror="yes" classname="myPackage.myPathName" classpath="build">
<arg line=""/>
<classpath>
<pathelement location="bin" />
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
</classpath>
</java>
And when this runs I see the “Thread timed out and never died” statement, and I also see the main program finish execution, but then Ant just hangs. Presumably it is waiting for the child threads to finish, but they never will.
How can I have Ant be done once it is done executing main() and just kill or ignore dead threads?
You can use
public final void setDaemon(boolean on)method of the Thread class i.eactionThread.setDaemon(true). That way you will ensure that JVM exits once the main Thread is finished.Java Doc says:
UPDATE
System.exit() Vs Daemon thread
For a bigger piece of code you cannot always be sure that all the
activethreads are the daemon threads. If a new thread is created by the daemon thread and if its setDaemon(true) is not set then it will inherit it from the parent. Although there can be scenarios where the newly created thread is set as a non-daemon (and then we will face your current problem).I personally think if you are done then you can call System.exit(0);
As per Java doc for System.exit():
There are other SO post where they have discussed this:
When should we call System.exit in Java
From which thread should System.exit() be called in a Swing-app?
As a third solution (1st is System.exit() , 2nd setDaemon()) you can also check for interrupted threads before doing any processing or decide ‘what to do’ in the handling of InterruptedException.
Hope this will help.