Monday, 8 May 2017

17. Reentrance synchronization vs multiple locks

1. What is object lock, when it is required
1.       Every object in java has lock is called as Object lock for executing synchronized method or block.
2.       Whenever thread wants to execute synchronized instance method or block with object then object lock is required.
2. What is class level lock, when it is required
1.       Every Class in java has lock is called as class level lock for executing static synchronized method or block.
2.       Whenever thread wants to execute static synchronized method or block with class then class lock is required.
3. Is that possible Thread can have multiple locks
1.       Yes, it’s possible thread can hold multiple locks.
Class X{
  public synchronized void m1(){//here thread has x lock
        Y y = new Y();
        synchronized(y){//here thread has locks of x,y
              Z z = new Z();
              Synchronized(z){
                    //Here thread has 3 locks of x,y,z
              }
        }
  }
}


→ Thread locks ‘this’, ‘s’ - string object, Display.class object


→ Thread locks ‘this’, ‘s’ - string object, Display.class object, Display.class
→ Thread locks ‘this’, ‘s’ - string object, Display.class object, ‘this’
4. Reentrance synchronization
  1. Synchronization is built around an internal entity known as the intrinsic lock or monitor lock.
  2. By default jvm locks the ‘this’ object for synchronized methods called as intrinsic lock with default object.
  3. We call lock the any specific object by using synchronized block called as intrinsic lock with specified object.
  4. If Synchronized method calls another synchronized method by same thread then thread locks the same object twice.
  5. When second synchronized method completes it releases the second object lock only.
  6. So in java, thread can have reentrance synchronization, means thread can lock same object more than once also by re entered into the synchronized method once again
    Synchronized   void  wish(){
    wish();
    }
  7. In above example same thread will entered into wish() in recursively, so thread locks infinite number of ‘this’ object lock.
  8. Below is example of reentrance synchronization
5. Multiple locks vs Reentrance synchronization
Multiple locks
Reentrance synchronization
thread can hold more than lock of same or different locks.
Thread can hold more than one lock of same lock
Every Multiple lock is not a reentrance lock.
Every Reentrance lock is multiple lock


No comments:

Post a Comment

3. Java Program to create Binary Tree