kavai77
kavai77

Reputation: 6616

Daemon Thread prevents JVM from terminating - possible reasons?

I need to develop a maven plugin that can start an apache ftp-server, run it as a daemon (does not halt the build process) and stop it as another goal. Unfortunately my first attempt to with daemon threads fails:

public class FtpServerDaemon
{
    public static void main(final String[] args) throws Exception
    {
        Thread thread = new Thread(new Runnable()
                {
                    @Override public void run()
                    {
                        org.apache.ftpserver.main.Daemon.main(args);
                    }
                });

        thread.setDaemon(true);
        thread.start();
        Thread.sleep(10000);
    }
}

The bad thing here is that the JVM does not terminate after 10 seconds but it runs indefinitely. If the Daemon.main is a black-box code (however the source is available), what can prevent the JVM from terminating in a daemon thread?

Upvotes: 0

Views: 2031

Answers (2)

kavai77
kavai77

Reputation: 6616

The FtpServer starts non-daemon threads and they are still running. If a thread is spawned from a daemon thread, the new thread will initially inherit the daemon status from its parent, but one can override it. E.g.:

Thread thread = new Thread(new Runnable()
                {
                    @Override public void run()
                    {

                        Thread embeddedNonDaemon = new Thread(new Runnable()
                                {
                                    @Override public void run()
                                    {
                                        while (true)
                                        {
                                            ;
                                        }
                                    }
                                });

                        embeddedNonDaemon.setDaemon(false);
                        embeddedNonDaemon.start();
                    }
                });

        thread.setDaemon(true);
        thread.start();
        Thread.sleep(5000);

This code does not terminate, either.

Upvotes: 0

RuntimeException
RuntimeException

Reputation: 1643

Agree with assylias and chrylis comments.

Instead of org.apache.ftpserver.main.Daemon.main(args); can you try some other code there? A loop that lasts more than the time the main thread sleeps should do, printing a number every n seconds or something.

I believe it must then terminate properly. Just to test whether the ftpserver is preventing the exit.

By the way, if a Daemon thread spawns a child thread, the child threads are automatically set as Daemon, right? So why this might be happening?

Upvotes: 1

Related Questions