Asdfasf

Thursday, August 01, 2013

Daemon Threads in Java

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).

Threads in java are created as non daemon default,  and the prolongs life time of application

Lets explain with examples

Example 1:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package test;

import java.util.Timer;
import java.util.TimerTask;

public class DeamonThreadTest {
 public static void main(String[] args) throws InterruptedException {
  Timer timer = new Timer();
  
  timer.schedule(new TimerTask(){

   @Override
   public void run() {
    System.out.println(System.currentTimeMillis());
   }
   
  }, 1000, 1000);    
 }
}

In example 1, process prints current time at each 1 sec period endlessly since thread of Timer is non deamon, and JVM waits for job completion of that thread.

Example 2:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package test;

import java.util.Timer;
import java.util.TimerTask;

public class DeamonThreadTest {
 public static void main(String[] args) throws InterruptedException {
  Timer timer = new Timer(true);
  
  timer.schedule(new TimerTask(){

   @Override
   public void run() {
    System.out.println(System.currentTimeMillis());
   }
   
  }, 1000, 1000);    
 }
}

In example 2, nothing is printed and process is terminated without waiting timer to do its job since Timer thread is created as daemon, see line 8.

Example 3:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package test;

import java.util.Timer;
import java.util.TimerTask;

public class DeamonThreadTest {
 public static void main(String[] args) throws InterruptedException {
  Timer timer = new Timer(true);
  
  timer.schedule(new TimerTask(){

   @Override
   public void run() {
    System.out.println(System.currentTimeMillis());
   }
   
  }, 1000, 1000);
  
  Thread.sleep(10000);
 }
} 

In example 3, timer gets chance to execute during 10 seconds since main thread waits 10 sec (see line 19) and than process is terminated since main thread does its job after line 19 and thread of timer is a daemon thread which does not prevent JVM to terminate the process.

No comments: