Saturday, 1 March 2014

Thread Prioritization

By giving priorities to threads, we tell the JVM, give more importance to Highest priority threads, and low importance to low priority threads.

1. How to get the priority of a Thread
    java provides getPriority(), to get the priority of a running thread.

    Syntax
    public final int getPriority()

Returns this thread's priority. This method is final, so we can't override this method

2. By Default main thread runs at the priority of 5.
Example 
class ThreadPriorityEx{
 public static void main(String args[]){
  System.out.println("Main Thread Priority is " + Thread.currentThread().getPriority());
 }
}
   
 Output
Main Thread Priority is 5
   

3. How to set the priority to a Thread
java provides setPriority(), to set the priority of a running thread.

Syntax
public final void setPriority(int newPriority)

Changes the priority of this thread.

4. when a new Thread is constructed, it runs at the same priority as the thread that constructed it.
Example

class ThreadPriorityEx implements Runnable{
 public void run(){
  System.out.println(Thread.currentThread().getName() + "Priority is" + Thread.currentThread().getPriority());
 }
 
 public static void main(String args[]){
  ThreadPriorityEx task = new ThreadPriorityEx();
  Thread.currentThread().setPriority(8);
  
  System.out.println("Main Thread Priority is " + Thread.currentThread().getPriority());
  
  Thread t1 = new Thread(task);
  t1.setName("MyThread");
  t1.start();
 }
}
   
 Output
Main Thread Priority is 8
MyThreadPriority is 8
   
5. Thread Priority Constants
Thread API provides three constants that specify thread priorities

static int MAX_PRIORITY
The maximum priority that a thread can have. Generally this value is 10.

static int MIN_PRIORITY
The minimum priority that a thread can have. Generally this value is 1.

static int NORM_PRIORITY
The default priority that is assigned to a thread. Generally this value is 5.

Example

class ThreadPriorityEx{
 public static void main(String args[]){
  System.out.println("Maximum priority of a thread is " + Thread.MAX_PRIORITY);
  System.out.println("Minimum priority of a thread is " + Thread.MIN_PRIORITY);
  System.out.println("Normal priority of a thread is " + Thread.NORM_PRIORITY);
 }
}
 
 Output
Maximum priority of a thread is 10
Minimum priority of a thread is 1
Normal priority of a thread is 5

6. If you try to set a priority which is less than MIN_PRIORITY and greater than MAX_PRIORITY, then program compiles fine, but throws “IllegalArgumentException” at run time.

Example  
class ThreadPriorityEx implements Runnable{
 public void run(){
 
 }
 
 public static void main(String args[]){
  ThreadPriorityEx task1 = new ThreadPriorityEx();
  
  int priority1 = Thread.MAX_PRIORITY + 1;
  int priority2 = Thread.MIN_PRIORITY - 1;
  
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  
  t1.setPriority(priority1);
  t2.setPriority(priority2);
 }
}
   
 Output
Exception in thread "main" java.lang.IllegalArgumentException
        at java.lang.Thread.setPriority(Unknown Source)
        at ThreadPriorityEx.main(ThreadPriorityEx.java:16)
   
Thread group priorities reflect the thread priorities. Will discuss about more on these in the Thread Group post.



Daemon Threads                                                 Give up resources                                                 Home

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