Thursday 8 January 2015

Textual Representation of logo

Java MultiThreading Interview Question

What would be the output of the following program ?


public class ThreadTest implements Runnable
{
 private Object obj=new Object();


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

 @Override
 public void run()
 {
  synchronized(obj)
  {
   System.out.println("1 " + Thread.currentThread().getId());
   obj = new Object();
   System.out.println("2 " +Thread.currentThread().getId());
  }
  
 }
}


Answer : The lock will break. The reason is that each and every object has got its own Object Monitor. Modifying the object means we will have a new lock object with new monitor. In such a case, lock will break and cause all the threads in the entry set to acquire the monitor.