Saturday, 1 March 2014

Daemon Threads

Daemon threads are low priority threads, which are mainly used for background processing

How to make a thread Daemon
Syntax
public final void setDaemon(boolean on)

When you set the setDaemon to true for a thread, then it acts as a daemon thread.

How to know whether a thread is daemon or not
Syntax:
isDaemon()

returns true if this thread is a daemon thread; false otherwise.

Notable points
1. The Java Virtual Machine exits when the only threads running are all daemon threads.

Example
class MyThread implements Runnable{
 public void run(){
  while(true){
   System.out.println("My Name is " + Thread.currentThread().getName());
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  Thread t3 = new Thread(task1);

  t1.setDaemon(true);
  t2.setDaemon(true);
  t3.setDaemon(true);

  t1.start();
  t2.start();
  t3.start();
 }
}
         
Sample Output      
 My Name is Thread-0

Observation
Above program has 3 threads. All the threads are set to daemon. If the threads are not set to daemon, then the program will run infinitely. In the above program all the threads are daemon, So once the main thread finishes its exection, JVM don't bother about the daemon threads. It simply quits.

2. SetDaemon() must be called before the thread is started. If you call setDaemon() after calling the Thread start method, setDaemon() throws IllegalThreadStateException.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   System.out.println("I am feeling sleepy");
   Thread.currentThread().sleep(5000);
   System.out.println("Time to work");
  }
  catch(InterruptedException e){
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);

  t1.start();
  t1.setDaemon(true);

 }
}
   
Sample Output

I am feeling sleepyException in thread "main"
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Unknown Source)
at MyThread.main(MyThread.java:22)
Time to work




Clear interrupted status                                                 Threads priority                                                 Home

Clear the interrupted status : interrupted()

Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).

Syntax
public static boolean interrupted()

returns true if the current thread has been interrupted; false otherwise

interrupted method clears the status of interrupted status flag. Where as isInterrupted() doesn't.

Example
class MyThread implements Runnable{
 public void run(){
  for(int i=0; i <1000000000; i++){
   int k = i+1, j=i;
   k = i/k;
   k = k*i;
  }
  System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
  System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
  System.out.println("Is thread interrupted " + Thread.interrupted());
  System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}
     
Output   
Is thread interrupted true
Is thread interrupted true
Is thread interrupted true
Is thread interrupted false

Notable points
1. Sleep() clears the interrupted flag status, before throwing InterruptedException
class MyThread implements Runnable{
 public void run(){
  try{
   for(int i=0; i <1000000000; i++){
    int k = i+1, j=i;
    k = i/k;
    k = k*i;
   }
   System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
   System.out.println("Is thread interrupted " + Thread.currentThread().isInterrupted());
  }
 }
 
 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}

 Output
Is thread interrupted true
Is thread interrupted false



Interrupted status of thread                                                 Daemon threads                                                 Home

Know the interrupted status of the thread

How to know whether a thread is interrupted or not
Thread API provides a method called, isInterrupted(), which returns true if the thread is interrupted, otherwise returns false.

Syntax
public boolean isInterrupted()

Tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method. Returns true if the thread is interrupted otherwise return false.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(5000);
  }
  catch(Exception e){
   try{
    Thread.currentThread().sleep(5000);
    System.out.println("Somebody interrupted me");
   }
   catch(InterruptedException e1){
   }
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
 }
}

Output   
Is thread1 interrupted true
Somebody interrupted me

Notable points
1. A thread interruption ignored, if a thread was not alive at the time of the interrupt called
i.e., if the thread finishes its execution, and you call the interrupted() after thread finishes its execution, it will returns false.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
  
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
  }
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
 }
}

Output   
Somebody interrupted me
Is thread1 interrupted false

2. If a thread is interrupted before it started, then nothing will happen, so isInterrupted() also return false
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(2000);
  }
  catch(Exception e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task1 = new MyThread();
  Thread t1 = new Thread(task1);
  t1.interrupt();
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
  t1.start();
  System.out.println("Is thread1 interrupted " + t1.isInterrupted());
 }
}

Output

Is thread1 interrupted false
Is thread1 interrupted false



Interrupt thread                                                 Clear interrupt status                                                 Home

Thread Interrupt : interrupt()

How to interrupt a Thread
You can interrupt a thread using interrupt() of Thread API.

Syntax
public void interrupt()

Notable points related to interrupt() method
1. When you interrupt a thread which is sleeping, then the sleep throws InterruptedException

Example
class MyThread implements Runnable{
 public void run(){
  try{
   System.out.println("I am so tired, going to sleep");
   Thread.currentThread().sleep(5000);
   System.out.println("Time to work");
  }
  catch(InterruptedException e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.start();
  t1.interrupt();
 }
}

Output
I am so tired, going to sleep
Somebody interrupted me
  
2. Nothing will happen if you interrupt the thread before calling start() method of the thread.

Example
class MyThread implements Runnable{
 public void run(){
  try{
   System.out.println("I am so tired, going to sleep");
   Thread.currentThread().sleep(5000);
   System.out.println("Time to work");
  }
  catch(InterruptedException e){
   System.out.println("Somebody interrupted me");
  }
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.interrupt();
  t1.start();
 }
}
   
Output
I am so tired, going to sleep
Time to work

3. If the thread has pending interrupt, and if it calls the sleep() with pending interrupts, then sleep throws an InterruptedException

class MyThread {
 public static void main(String args[]){
  Thread.currentThread().interrupt();
  try{
   Thread.currentThread().sleep(100);
  }
  catch(InterruptedException e){
   System.out.println("Somebody interrupted me");
  }
 }
}
    
Output
Somebody interrupted me
    



Thread sleep                                                 interrupted status of thread                                                 Home

Make a thread sleep :sleep()

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of time

A sleeping thread does not use any processor cycles because its execution is suspended for the specified duration.

Thread API provides 2 Methods to make a thread to sleep
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException

sleep method throws InterruptedExceiption, If a sleeping thread interrupted , it throws Interrupted Exception. Will see more details in the Interrupts section.

public static void sleep(long millis) throws InterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. Will discuss about acquiring abut monitor in synchronization topic

public static void sleep(long millis, int nanos) throws InterruptedException
Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds. The thread does not lose ownership of any monitors. Better don't depend on nano seconds, they are depend on the underlying system Architecture.

sleep is a static method, so we have to call by class name.

You must handle the Interrupted Exception, otherwise compiler will throw error.

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("About to call sleep method");
  Thread.sleep(1000);
  System.out.println("sleep time finished");
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.start();
 }
}

When you try to compile, you will get the compile time error

MyThread.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown
Thread.sleep(1000);
^
1 error

To make the above program run, handle the exception

class MyThread implements Runnable{

 public void run(){
  System.out.println("About to call sleep method");
  try{
   Thread.sleep(1000);
  }
  catch(InterruptedException e){
  }
  System.out.println("sleep time finished");
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread t1 = new Thread(task);
  t1.start();
 }
}
     
Output
About to call sleep method
sleep time finished



Thread live status                                                 Interrupt Thread                                                 Home

thread status isAlive

A Thread remains alive until it returns from the run() method, or or until the thread is abruptly stopped by the stop()method. Simply A thread is alive if it has been started and has not yet died. Stop method is deprecated.

Syntax
public final boolean isAlive()
returns true if this thread is alive; false otherwise.

isAlive() is a final method, so you can't override it. isAlive() method returns false before calling the start method

Example
class MyThread implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
  }
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread task = new MyThread();
  Thread thrd = new Thread(task);
  
  System.out.println("Thread before calling start " + thrd.isAlive());
  thrd.start();
  System.out.println("thread after calling start " + thrd.isAlive());
  
  try{
   thrd.join();
  }
  catch(InterruptedException e){

  }
  System.out.println("thread after finishes execution " + thrd.isAlive());
  System.out.println(thrd.isAlive());
 }
}
 

Output
Thread before calling start false
thread after calling start true
Thread name is Thread-0
thread after finishes execution false
false
   
Observation
See the output the isAlive() method returns false, before calling the start(). Sleep method makes the thread to wait for some time. join method waits until the thread on which it is called finishes execution. Don't worry much abut sleep() an join(), you will see more about these soon.



Thread constructors                                                 Thread sleep                                                 Home

Friday, 28 February 2014

Thread API : Constructors

Thread class provides 8 different types of constructors.

Those are:
1. Thread()
2. Thread(Runnable target)
3. Thread(Runnable target, String name)
4. Thread(String name)
5. Thread(ThreadGroup group, Runnable target)
6. Thread(ThreadGroup group, Runnable target, String name)
7. Thread(ThreadGroup group, Runnable target, String name, long stackSize)
8. Thread(ThreadGroup group, String name)

We will discuss about the first four constructors now. Remaining will be discussed at the time of learning Thread Groups.

1. public Thread()
Creates a Thread object.

2. Thread(Runnable target)
Allocates a new Thread object. Assign the Runnable task to it

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  Thread t2 = new Thread(t1);
  t2.start();
 }
}

Output
Thread name is Thread-0

3. Thread(Runnable target, String name)
Allocates a new Thread object. Assign the Runnable task to it and Assign a name to the thread. When you call the start method, then thread will start executing the run method of the Runnable object

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  Thread t2 = new Thread(t1, "My Thread 1");
  t2.start();
 }
}

Output
Thread name is My Thread 1

4. Thread(String name)
Allocates a new Thread object. Assign a name to the thread

Example
class MyThread extends Thread{
 MyThread(String name){
  super(name);
 }

 public void run(){
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread("My Thread 1");
  t1.start();
 } 
}
 
Output
Thread name is My Thread 1

Exploring thread API                                                 Thread running status                                                 Home