Recent Posts

Monday, 8 August 2016

Threads And Concurrency Tutorial Part 4


Dead lock
* If two Threads are waiting for each other forever(without end) such type of situation(infinite waiting) is called dead lock.

* There are no resolution techniques for dead lock but several prevention(avoidance) techniques are possible.

* Synchronized keyword is the cause for deadlock hence whenever we are using synchronized keyword we have to take special care.
E.g
package com.ashok.threads;

class Ashok {
   synchronized void foo(Vinod vinod) {
      System.out.println("Thread 1 entered foo() method");
      try {
         Thread.sleep(600);
      } catch (InterruptedException e) {
   }
      System.out.println("Thread 1 is trying to call vinod.last()");
      vinod.last();
   }

   synchronized void last() {
      System.out.println("Inside Ashok, This is last() method");
   }
}

class Vinod {
   synchronized void bar(Ashok ashok) {
      System.out.println("Threas 2 entered bar() method");
      try {
         Thread.sleep(600);
      } catch (InterruptedException e) {
      }
      System.out.println("Thread 2 is trying to call ashok.last()");
      ashok.last();
   }

   synchronized void last() {
      System.out.println("Inside Vinod, This is last() method");
   }
}

public class MyDeadLock implements Runnable {
   Ashok ashok = new Ashok();
   Vinod vinod = new Vinod();

   MyDeadLock() {
      Thread t = new Thread(this);
      t.start();
      vinod.bar(ashok);
   }

   public void run() {
      ashok.foo(vinod);
   }

   public static void main(String arg[]) {
      new MyDeadLock();
   }
}

Output
Threas 2 entered bar() method
Thread 1 entered foo() method
Thread 2 is trying to call ashok.last()
Thread 1 is trying to call vinod.last()
...
...
...
// Here cursor always waiting.
DaemonThread
     The threads which hare running in the background to provide support for user defined threads are called “Daemon Thread”. Usually daemon thread are running with low priority but based on our requirement we can increase their priority also. The main objective of daemon Threads is to provide support for non-daemon Threads like main Thread.
E.g
Garbage collector

     When ever the program runs with low memory the JVM will execute Garbage Collector to provide free memory. So that the main Thread can continue it's execution.

* We can check whether the Thread is daemon or not by using isDaemon() method of Thread class.
public final boolean isDaemon();

* We can change daemon nature of a Thread by using setDaemon () method.
public final void setDaemon(boolean b);

* But we can change daemon nature before starting Thread only. That is after starting the Thread if we are trying to change the daemon nature we will get R.E saying IllegalThreadStateException.

* Default Nature
     Main Thread is always non daemon and we can't change its daemon nature because it's already started at the beginning only.

* Main Thread is always non daemon and for the remaining Threads daemon nature will be inheriting from parent to child that is if the parent is daemon child is also daemon and if the parent is non daemon then child is also non daemon.

* Whenever the last non daemon Thread terminates automatically all daemon Threads will be terminated.
E.g
package com.ashok.threads;

class MyThread extends Thread {

}

public class MyDaemonThread {
   public static void main(String[] args) {
      System.out.println(Thread.currentThread().isDaemon());
      MyThread t = new MyThread();
      System.out.println(t.isDaemon());
      t.start();
      t.setDaemon(true);
      System.out.println(t.isDaemon());
   }
}
Output
false
false
RE:IllegalThreadStateException
package com.ashok.threads;

class MyThread extends Thread {
   public void run() {
      for (int i = 0; i < 10; i++) {
         System.out.println("Child thread");
         try {
            Thread.sleep(2000);
         } catch (InterruptedException e) {
         }
      }
   }
}

public class MyDaemonThread {
   public static void main(String[] args) {
      MyThread thread = new MyThread();
      thread.setDaemon(true); 
      thread.start();
      System.out.println("Main Thread");
   }
}
Output
Main Thread
Child thread
     If we comment line thread.setDaemon(true); then both main & child Threads are non-Daemon , and hence both threads will be executed untill there completion.
     If we are not comment line thread.setDaemon(true); then main thread is non-Daemon and child thread is Daemon. Hence when ever main Thread terminates automatically child thread will be terminated.

Note
* We can call stop() method to stop a Thread in the middle then it will be entered into dead state immediately.
public final void stop();

* stop() method has been deprecated and hence not recommended to use.

* A Thread can suspend another Thread by using suspend() method then that Thread will be paused temporarily.
 
* A Thread can resume a suspended Thread by using resume() method then suspended Thread will continue its execution.
public final void suspend();
public final void resume();

* Both methods are deprecated and not recommended to use.

RACE condition
     Executing multiple Threads simultaneously and causing data inconsistency problems is nothing but Race condition. We can resolve race condition by using synchronized keyword.

ThreadGroup
     Based on functionality we can group threads as a single unit which is nothing but ThreadGroup.

     ThreadGroup provides a convenient way to perform common operations for all threads belongs to a perticular group.

     We can create a ThreadGroup by using the following constructors
ThreadGroup g=new ThreadGroup(String gName);

     We can attach a Thread to the ThreadGroup by using the following constructor of Thread class
Thread t=new Thread(ThreadGroup g, String name);
ThreadGroup tgroup=new ThreadGroup("Printing Threads");
MyThread t1=new MyThread(tgroup,"Header Printing");
MyThread t2=new MyThread(tgroup,"Footer Printing");
MyThread t3=new MyThread(tgroup,"Body Printing");
-----------
tgroup.stop();
Note
     Java Multi Threading concept is implementing by using the following 2 methods :
1. GreenThread Model
2. Native OS Model

GreenThread Model
     The threads which are managed completely by JVM without taking support for underlying OS, such type of threads are called Green Threads.

Native OS Model
* The Threads which are managed with the help of underlying OS are called Native Threads.
* Windows based OS provide support for Native OS Model

* Very few OS like SunSolaries provide support for GreenThread Model
* Anyway GreenThread model is deprecated and not recommended to use.

Next Tutorial  File I/O & Serialization Tutorial

Previous Tutorial  Threads and Concurrency Tutorial Part 4

1 comment: