简体   繁体   中英

Why need use non-daemon threads in java?

It seems that daemon threads are always better - because they will be stopped by the VM after application main thread exits. Are there any other reasons to use non-daemon threads besides the cases when it is not possible to interrupt some operation ? Thanks.

When you are writing a server (eg a servlet container), all your main has to do is to bootstrap and start HTTP listener threads, accepting threads, file system scanning threads, RMI threads, etc.

After bootstrap is done, main is no longer needed as everything happens asynchronously. In this case all essential threads are non-daemon as they have to live past the main method.

Even in Swing (desktop programming) the only requirement on main is to initialize the main window ( JFrame ). The rest happens in Swing listener threads (EDT) and various background threads.

In fact, any thread that should finish naturally (leaving its "run" method) should not be a daemon thread, as you don't want the JVM to terminate while they are doing their job.

This applies to every thread that you launch, and that you expect to terminate naturally.

As a rule of thumb, daemon threads are the exception, not the rule.

The one major difference is in how daemon threads exit; the JVM just stops them.

  • finally blocks are not executed
  • stacks are not unwound

You do not want to use daemon threads for things that need to be left in a known state such as file i/o, database transactions, etc.

You use non-daemon thread whenever you are doing something which you don't want to stop because an another thread exits. If the only purpose of a thread is to support other threads, then it makes sense to use a daemon thread.

If you want to exit when the main thread exits you can call System.exit(). Many applications don't keep their main thread and all the work is in threads it starts.

The VM may stop daemon threads in the middle of their executions, and persistent data could be corrupted because of that.

If you need more control of when a thread is safe to die, do not make it a daemon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM