Monday, 3 March 2014

getAllStackTraces : Get the Stack traces of all Threads

public static Map<Thread,StackTraceElement[]> getAllStackTraces()
Returns a map of stack traces for all live threads. The map keys are threads and each map value is an array of StackTraceElement that represents the stack dump of the corresponding Thread. The returned stack traces are in the format specified for the getStackTrace method.

Example
import java.util.*;
class ThreadStackTrace implements Runnable{

 void print(){
  show();
 }

 void show(){
  display();
 }

 void display(){
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
  }
 }

 public void run(){
  print();
 }

 public static void main(String args[]){
  ThreadStackTrace task1 = new ThreadStackTrace();

  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);
  Thread t3 = new Thread(task1);

  t1.start();
  t2.start();
  t3.start();

  Map<Thread, StackTraceElement[]> obj = Thread.getAllStackTraces();
  Set<Thread> s1 = obj.keySet();
  Iterator<Thread> i1 = s1.iterator();

  while(i1.hasNext()){
   Thread key = i1.next();
   System.out.println("Trace information for the thread " + key);
   StackTraceElement[] trace = obj.get(key);

   for(int i=0; i < trace.length; i++){
    System.out.println(trace[i]);
   }
   System.out.println();
  } 
 }
}
   
Output
Trace information for the thread Thread[Reference Handler,10,system]
   java.lang.Object.wait(Native Method)
   java.lang.Object.wait(Object.java:503)
   java.lang.ref.Reference$ReferenceHandler.run(Reference.java:133)

   Trace information for the thread Thread[Thread-1,5,main]
   java.lang.Thread.sleep(Native Method)
   ThreadStackTrace.display(ThreadStackTrace.java:24)
   ThreadStackTrace.show(ThreadStackTrace.java:19)
   ThreadStackTrace.print(ThreadStackTrace.java:15)
   ThreadStackTrace.run(ThreadStackTrace.java:31)
   java.lang.Thread.run(Thread.java:722)

   Trace information for the thread Thread[Attach Listener,5,system]

   Trace information for the thread Thread[main,5,main]
   java.lang.Thread.dumpThreads(Native Method)
   java.lang.Thread.getAllStackTraces(Thread.java:1618)
   ThreadStackTrace.main(ThreadStackTrace.java:44)

   Trace information for the thread Thread[Thread-2,5,main]

   Trace information for the thread Thread[Finalizer,8,system]
   java.lang.Object.wait(Native Method)
   java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:135)
   java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:151)
   java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:177)

   Trace information for the thread Thread[Thread-0,5,main]
   java.lang.Thread.sleep(Native Method)
   ThreadStackTrace.display(ThreadStackTrace.java:24)
   ThreadStackTrace.show(ThreadStackTrace.java:19)
   ThreadStackTrace.print(ThreadStackTrace.java:15)
   ThreadStackTrace.run(ThreadStackTrace.java:31)
   java.lang.Thread.run(Thread.java:722)

   Trace information for the thread Thread[Signal Dispatcher,9,system]

   
As you observe the output, It includes the trace information of all the thread like user define, main thread and Background processing threads.

You can read the below posts for more information about Stack Trace.



Get stack trace                                                 Active Threads Count                                                 Home

getStackTrace : Get the Stack trace of a thread

public StackTraceElement[] getStackTrace()
Returns an array of stack trace elements representing the stack dump of this thread. The last element of the returned array represents the bottom of the stack, where as the top element represents the most recent method invocation call.

Example
class ThreadStackTrace implements Runnable{
 void print(){
  show();
 }

 void show(){
  display();
 }

 void display(){
  StackTraceElement[] trace = Thread.currentThread().getStackTrace();
  for(int i=0; i < trace.length; i++)
   System.out.println(trace[i]);
 }

 public void run(){
  print();
 }

 public static void main(String args[]){
  ThreadStackTrace task1 = new ThreadStackTrace();
  Thread t1 = new Thread(task1);
  t1.start();
 }
}
   
Output
java.lang.Exception: Stack trace
 at java.lang.Thread.dumpStack(Thread.java:1342)
 at ThreadStackTrace.display(ThreadStackTrace.java:22)
 at ThreadStackTrace.show(ThreadStackTrace.java:18)
 at ThreadStackTrace.print(ThreadStackTrace.java:14)
 at ThreadStackTrace.run(ThreadStackTrace.java:26)
 at java.lang.Thread.run(Thread.java:722)

Print current stack trace                                                 Get All Stack traces                                                 Home

dumpStack : Print current Stack Trace of Thread

public static void dumpStack()
Prints a stack trace of the current thread to the standard error stream. As you see the implementation of dumpStack(), it calls the printStackTrace() Of the Exception class.

   public static void dumpStack() {
      new Exception("Stack trace").printStackTrace();
   }

Example
class ThreadStackTrace implements Runnable{
 void print(){
  show();
 }

 void show(){
  display();
 }

 void display(){
  Thread.currentThread().dumpStack();
 }

 public void run(){
  print();
 }

 public static void main(String args[]){
  ThreadStackTrace task1 = new ThreadStackTrace();
  Thread t1 = new Thread(task1);
  t1.start();
 }
}
    
Output
java.lang.Exception: Stack trace
 at java.lang.Thread.dumpStack(Thread.java:1342)
 at ThreadStackTrace.display(ThreadStackTrace.java:22)
 at ThreadStackTrace.show(ThreadStackTrace.java:18)
 at ThreadStackTrace.print(ThreadStackTrace.java:14)
 at ThreadStackTrace.run(ThreadStackTrace.java:26)
 at java.lang.Thread.run(Thread.java:722)

You can read the below posts for more information about Stack Trace



Dead Lock Example                                                 Get stack trace                                                 Home

Sunday, 2 March 2014

java Dead lock Example



Dead lock is a situation where two or more threads block forever. In Operating system dead lock occurs, when one process or thread is waiting for a resource, where this resource is in use by other process, which in turn waiting for other resource.

Dead lock is a common problem in multi threading environment. Care must be taken while developing multi threading Applications.

As you see the above figure,
process p1, acquires the resource R1, and waiting for the resource R2
process p2 acquires the resource R2, and waiting for the resource R1.

P1 releases the resource R1, once it finishes its task, but to finish its task, p1 needs rsource R1, which is in use by p2, so process p1 waits infinitely. Same thing happen with p2 also. So it is a deadlock, where processes p1 and p2 waiting infinitely.

Will implement the same model to create a dead lock using java.

interface Resource{
 void startExec(Resource r)throws Exception;
 public void end();
}

class Resource1 implements Resource{
 synchronized public void startExec(Resource r2)throws Exception{
  Thread.currentThread().sleep(2000);
  System.out.println(Thread.currentThread().getName() + " started \nAbout to call the end method of resource r2");
  r2.end();
 }

 synchronized public void end(){
  System.out.println("End");
 }
}
  

class Resource2 implements Resource{
 synchronized public void startExec(Resource r1)throws Exception{
  Thread.currentThread().sleep(2000);
  System.out.println(Thread.currentThread().getName() + " started \nAbout to call the end method of resource r1");
  r1.end();
 }

 synchronized public void end(){
  System.out.println("End");
 }
}

class DeadLockEx implements Runnable{
 Resource r1, r2;

 public void run(){
  try{
   r1.startExec(r2);
  }
  catch(Exception e){
  }
 }

 DeadLockEx(Resource r1, Resource r2){
  this.r1 = r1;
  this.r2 = r2;
 }

 public static void main(String args[]){
  Resource1 r1 = new Resource1();
  Resource2 r2 = new Resource2();

  DeadLockEx obj1 = new DeadLockEx(r1, r2);
  DeadLockEx obj2 = new DeadLockEx(r2, r1);

  Thread task1 = new Thread(obj1);
  Thread task2 = new Thread(obj2);

  task1.setName("p1");
  task2.setName("p2");

  task1.start();
  task2.start();
 }
}

Output   
p1 started
About to call the end method of resource r2
p2 started
About to call the end method of resource r1

task1 calls the synchronized method startExec() of resource r1, so r1 is locked.
task2 calls the synchronized method startExec() of resource r2, so r2 is locked.

Task1 tries to call the synchronized method end() of resource r2, but r2 is locked, so it waits for the resource.

Task2 tries to call the synchronized method end() of resource r1, but r1 is locked, so it waits for the resource.

Task1 and task2 waits infinitely. So Deadlock happened.



Dead lock                                                 Print Current stack trace                                                 Home

Dead Lock

Dead Lock
Dead lock is a situation where two or more threads block forever. In Operating system dead lock occurs, when one process or thread is waiting for a resource, where this resource is in use by other process, which in turn waiting for other resource.


Dead lock is a common problem in multi threading environment. Care must be taken while developing multi threading Applications.




As you see the above figure,
process p1, acquires the resource R1, and waiting for the resource R2
process p2 acquires the resource R2, and waiting for the resource R1.


P1 releases the resource R1, once it finishes its task, but to finish its task, p1 needs rsource R1, which is in use by p2, so process p1 waits infinitely. Same thing happen with p2 also. So it is a deadlock, where processes p1 and p2 waiting infinitely.


Why Wait & Notify in Object class                                                 Java Dead Lock Example                                                 Home

Why Wait and Notify is in Object Class

In java, we are acquiring locks on the resources. Every Object treated as a resource in java. Since Java is multi threaded, there is a possibility for resource corruption, if multiple threads are working on the same resource. There should be a mechanism, to safely update the resource. Here the monitor concept came to picture.

While performing any update on the resource, a thread must acquire a lock on the resource. Then the thread which acquires lock on the resource, update the resource, remaining all threads which want to work on this resource must wait until it finishes. Once the the thread finishes its updation with the resource, it asks the resource, to notify remaining threads to update. Same procedure like acquiring lock, releasing lock, notifying other threads repeats.

Since in java every resource considers to be an object, so that wait, notify and notifyAll kept in Object class.


Thread States                                                 Dead Lock                                                 Home

Thread States

1. Once a thread starts executing it will be in one of below states
    a. Running
    b. Ready to Run (Waiting in the ready queue for their turn)
    c. sleeping
    d. waiting
    e blocked

2. Not all threads are interruptible, we can interrupt a thread which is sleeping or which is in waiting state. But if a thread block on I/O it will not respond to interrupts. When a thread is blocked waiting to get the lock required by a synchronized statement, it also will not respond to interrupt requests.

3. We can interrupt a thread that is sleeping 
class ThreadInterrupt implements Runnable{
 public void run(){
  System.out.println("Time to sleep");
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e){
   System.out.println(e);
  }
 }

 public static void main(String args[]){
  ThreadInterrupt task1 = new ThreadInterrupt();
  Thread t1 = new Thread(task1);
  t1.start();
  t1.interrupt();
 }
}
   
Output
Time to sleep
java.lang.InterruptedException: sleep interrupted

4. We can interrupt a thread that is waiting on particular object
class ThreadInterrupt implements Runnable{
 Object obj = new Object();

 public void run(){
  System.out.println("Time to sleep");
   synchronized(obj){
    try{
     obj.wait();
    }
    catch(InterruptedException e){
     System.out.println(e);
    }
   }
  }

  public static void main(String args[]){
   ThreadInterrupt task1 = new ThreadInterrupt();
   Thread t1 = new Thread(task1);
   t1.start();
   t1.interrupt();
  }
}
   
Output
Time to sleep
java.lang.InterruptedException

5. A Thread is not interruptible if it is waiting on I/O
import java.io.*;
class ThreadInterrupt implements Runnable{
 static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

 public void run(){
  try{
   System.out.println("Enter input");
   String s = br.readLine();
   System.out.println("You entered " +s);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }

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

Output
Enter input
PTR
You entered PTR
   
6. The difference between blocked and waiting state is, a thread which is in waiting state can be interruptible, where as, a thread which is blocked on acquiring lock or I/O is not interruptible


Notify Thread                                                 Thread states                                                 Home