Sunteți pe pagina 1din 2

What is Daemon thread?

Daemon thread in Java are those thread which runs in background and mostly
created by JVM for performing background task like Garbage collection and other house
keeping tasks. They are service providers for other threads running in the same process
as the daemon thread. To specify that a thread is a daemon thread, call the setDaemon
method with the argument true. To determine if a thread is a daemon thread, use the
accessor method isDaemon.
Important points about Daemon threads in Java
. !ny thread created by main thread, which runs main"# method in $ava is by default
non daemon because Thread inherits its daemon nature from the Thread which creates it
i.e. parent Thread and since main thread is a non daemon thread, any other thread
created from it will remain non%daemon until e&plicitly made daemon by calling
setDaemon"true#.
'. Thread.setDaemon"true# makes a Thread daemon but it can only be called before
starting Thread in Java. (t will throw (llegalThread)tate*&ception if corresponding
Thread is already started and running.
+. Daemon Threads are suitable for doing background $obs like housekeeping, Though (
have yet to use it for any practical purpose in application code. let us know if you have
used daemon thread in your $ava application for any practical purpose.
Difference between Daemon and Non Daemon thread in Java
# JVM doesn,t wait for any daemon thread to finish before e&isting.
'# Daemon Thread are treated differently than -ser Thread when JVM terminates,
finally blocks are not called, )tacks are not unwounded and JVM $ust e&its.
Daemon Thread Example in Java
.ere is a code e&ample of daemon thread in $ava. we make a user thread daemon by
calling setDaemon"true# and every time you run you will see variable number of print
statement related to /daemon thread is running/ you will never see print statement
written in finally block because finally will not be called.
That0s all on 1hat is Daemon Thread in Java and difference between Daemon and non
daemon thread in Java with code e&ample of Daemon thread in Java. JVM also uses
daemon thread for Garbage collection.
2ead more3 http344$avarevisited.blogspot.com4'5'45+4what%is%daemon%thread%in%$ava%
and.html6i&77+8h.Jf'9:

S-ar putea să vă placă și