user710818
user710818

Reputation: 24248

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.

Upvotes: 4

Views: 2248

Answers (5)

Brian Roach
Brian Roach

Reputation: 76908

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.

Upvotes: 4

Thiago Chaves
Thiago Chaves

Reputation: 9463

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.

Upvotes: 1

jjmontes
jjmontes

Reputation: 26944

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.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533690

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.

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340903

When you are writing a server (e.g. 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.

Upvotes: 6

Related Questions