Daemon thread - strange??

A

adeon

Hi folks,

I've encountered an odd daemon thread behavior.
Have a look at this simple example:

/** Non-daemon thread */
class R implements Runnable
{
public void run()
{
System.out.println("non-daemon is running");
System.out.flush();
try
{
Thread.sleep(5000); //wait 5s
}
catch (Exception e)
{
throw new RuntimeException(e);
}

System.out.println("non-daemon is exiting");
System.out.flush();
}
}


public class testClass
{
// main method
public static void main(String[] args)
{
//create an anonymous daemon thread
Thread t = new Thread(){
public void run()
{
System.out.println("daemon is starting");
//create non-daemon thread and start it
Thread t2 = new Thread(new R());
t2.setDaemon(false);
t2.start();
System.out.println("daemon is exiting");
}
};

t.setDaemon(true);
t.start();
try
{
//Thread.sleep(1000); (!!!!!)
}
catch (Exception e)
{}

System.out.println("main() finished");
System.out.flush();
}
}


What the code above does is that main() simply creates a daemon thread
't', whose run() method creates a *non*-daemon thread 't2'. Then
the daemon thread 't' is started. One could expect that _if_ the daemon
thread starts the non-daemon thread, the program should run at least for
5s (because, according to javadoc, the application runs as long as it's
all non-daemon threads run). But the output I get (when line marked
(!!!!!) is commented out) :

main() finished
daemon is starting
daemon is exiting
non-daemon is running

The "non-daemon is running" message means that the non-daemon thread
't2' was started, but the application didn't wait for it's finish!!
Is it a feature, a bug, or am I doing sth wrong?

On the other hand, when the line marked (!!!!) is not commented out, the
output is as I expected:

daemon is starting
daemon is exiting
non-daemon is running
(waits about 1s)
main() finished
(waits about 4s)
non-damon is exiting

It looks like there was a race condition in the first example, but my
opinion is that if a *non*-daemon thread is started, the application
should wait for it, even if that thread execution was started after
main() end.

Cheers
AD
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top