Why use non-daemon streams in java?

It seems that daemon threads are always better - because they will be stopped by the virtual machine after the main application thread exits. Are there any other reasons for using threads other than daemon, other than when it is not possible to abort some operation? Thanks.

+4
source share
5 answers

The VM can stop daemon threads in the middle of their execution, and permanent data can be corrupted due to this.

If you need more control when the thread is safe for death, do not make it a demon.

+1
source

When you write a server (for example, a servlet container), all your main should load and start HTTP listener streams, accept streams, file system scan threads, RMI streams, etc.

After the bootstrap is complete, main no longer required, as everything happens asynchronously. In this case, all significant threads are non-daemons, since they must live according to 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 Listening Streams (EDTs) and various background threads.

+6
source

In fact, any thread that should end naturally (leaving its "run" method) should not be a daemon thread, since you do not want the JVM to stop working while they do their work.

This applies to every running thread and what you expect to be naturally terminated.

As a rule, exceptions are an exception, not a rule.

+4
source

The only significant difference is how the daemon flows out; The JVM just stops them.

  • finally blocks are not executed
  • stacks do not unwind

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

+4
source

You use a non-daemon thread when you are doing something that you do not want to stop because another thread is terminating. If the sole purpose of the 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 do not save their main thread, and all work in the threads begins.

+2
source

Source: https://habr.com/ru/post/1390479/


All Articles