Java Threads: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 11: Line 11:


==Daemon Thread==
==Daemon Thread==
{{External|http://www.javaperspective.com/daemon-threads.html}}
A daemon thread is a thread that '''DOES NOT''' prevent the JVM from exiting, even if the thread is in WAITING or TIMED_WAITING state. Specifically the JVM will exit when only daemon threads remain.
When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound - JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.
When a new thread is created it inherits the daemon status of its parent. Or it can be set with setDaemon(true).
For more details on the relationship between non-daemon threads and JVM shutdown, see:
{{Internal|Java_Shutdown#Non-Daemon_Threads_and_.22Natural.22_Shutdown|Non-Daemon Threads and "Natural" Shutdown}}


==Java Threads and Linux Processes==
==Java Threads and Linux Processes==

Revision as of 18:26, 21 June 2017

Internal

Subjects

Concepts

Daemon Thread

http://www.javaperspective.com/daemon-threads.html

A daemon thread is a thread that DOES NOT prevent the JVM from exiting, even if the thread is in WAITING or TIMED_WAITING state. Specifically the JVM will exit when only daemon threads remain.

When the JVM halts any remaining daemon threads are abandoned: finally blocks are not executed, stacks are not unwound - JVM just exits. Due to this reason daemon threads should be used sparingly and it is dangerous to use them for tasks that might perform any sort of I/O.

When a new thread is created it inherits the daemon status of its parent. Or it can be set with setDaemon(true).

For more details on the relationship between non-daemon threads and JVM shutdown, see:

Non-Daemon Threads and "Natural" Shutdown

Java Threads and Linux Processes

On a Linux system, each JVM thread counts as a "process", in that it is subject to system-wide and user-wide process number limitations - see "maximum number of processes allowed on a system" and "maximum number of processes available to a single user". When a JVM instance adjust its number of threads, the change is reflected by /proc/stat "processes" count.

For an example of what happens when the number of Linux processes allowed to an user is reached, see

OutOfMemoryError "unable to create new native thread"

A simple Java program that allows experimenting with threads:

https://github.com/NovaOrdis/playground/tree/master/java/threads/multiple-threads-spinning

Java Thread Stack Memory Management

Thread Stack Memory Management

Difference between Blocked and Waiting

http://geekexplains.blogspot.com/2008/07/threadstate-in-java-blocked-vs-waiting.html