Urgent.News

What's breaking now, across thousands of outlets.

Tech

Should Your Thread Keep the JVM Alive?

Understanding daemon vs non-daemon threads Daemon vs non-daemon is one of those distinctions that seems trivial ("just a boolean flag") until you get bitten by it, and then you never forget it. The core difference The JVM has one simple rule for when to shut down: the JVM exits when all non-daemon threads have finished. Daemon threads are ignored in that calculation entirely. That is it. That is…

The JVM exits when all non-daemon threads have completed their execution, making daemon and non-daemon threads fundamentally different. Non-daemon threads, including the main thread and any threads created from it, ensure the JVM stays alive. Daemon threads, on the other hand, are ignored in the shutdown calculation and do not prevent the process from terminating.

In the default configuration, all threads are non-daemon. The distinction becomes crucial when considering the impact of the JVM's shutdown on user-perceived application behavior. Non-daemon threads keep threads running until their tasks are finished, making them suitable for critical application work such as user-initiated actions, financial transactions, or writing to persistent storage. If the JVM terminates while these threads are executing, the user may lose their work or experience significant delays.

Daemon threads, however, are ideal for background or optional tasks that are not essential to the application's immediate functionality. Examples include analytics uploaders, best-effort telemetry, heartbeats, and file writers. In these scenarios, if the JVM exits while a daemon thread is mid-task, the loss of the work is generally considered less detrimental than the cost of waiting for the thread to complete.

When deciding whether to make a thread daemon or non-daemon, ask yourself: does the JVM exiting while this thread is mid-task cause a problem? If so, the thread should be non-daemon. If not, it can be marked as a daemon. This principle applies across platforms, including Android, where the daemon flag has a less direct impact on JVM shutdown due to the runtime's component lifecycle management.

Nonetheless, the general principle remains: user-initiated, critical work should be non-daemon, while background or optional tasks are better suited as daemon threads.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Saturday 12 September →