synchronization blocks and methods in java - Acquiring object lock - multiple threads may exist on same object but only one thread of that object can enter synchronized block/method at a time.


In later posts we will learn how to acquire lock on class’s class object. Now, we will learn how to acquire object’s lock. It’s very important to understand difference between object lock and class lock as well.

Thread can acquire object lock by-
  1. Entering synchronized block or
  2. by entering synchronized methods.

wait(), notify()  and notifyAll() methods are always called from Synchronized block or synchronized methods only and as soon as thread enters synchronized block it acquires object lock (by holding object monitor).



1) First let’s acquire object lock by entering synchronized block.

Let’s say there is one class MyClass and we have created it’s object and reference to that object is myClass. Now we can create synchronization block, and parameter passed with synchronization tells which object has to be synchronized. In below code, we have synchronized object reference by myClass.
MyClass myClass=new Myclass();
      synchronized (myClass) {
        //thread has acquired object lock on object referenced by myClass ( by acquiring myClass’s monitor.)
      }

As soon thread entered Synchronization block, thread acquired object lock on object referenced by myClass (by acquiring object’s monitor.)
Thread will leave lock when it exits synchronized block.


Now, let’s create a program >
class MyRunnable implements Runnable {
  
   public void run() {
         
          synchronized (this) {
                 for(int i=0;i<5;i++){
                       System.out.println(i+" "+Thread.currentThread().getName()+" is executing");
                       try {
                              Thread.sleep(500);
                       } catch (InterruptedException e) {e.printStackTrace(); }
                 }
                
          }
   }
}
public class MyClass {
   public static void main(String args[]) throws Exception {
          MyRunnable obj = new MyRunnable();
          Thread t1 = new Thread(obj,"Thread-1");  //Thread-1 on obj.
          Thread t2 = new Thread(obj,"Thread-2"); //Thread-2 on obj.
          t1.start();
          t2.start();
   }
}
/*OUTPUT
0 Thread-1 is executing
1 Thread-1 is executing
2 Thread-1 is executing
3 Thread-1 is executing
4 Thread-1 is executing
0 Thread-2 is executing
1 Thread-2 is executing
2 Thread-2 is executing
3 Thread-2 is executing
4 Thread-2 is executing
*/
If we note output, Thread-1 entered synchronization block and acquired obj’s lock meanwhile Thread-2 kept on waiting for obj’s lock. And once Thread-1 completed Thread-2 acquired obj’s lock and started executing.



2) Now let’s acquire object lock by entering synchronized method.


Example- Let’s say there is one class MyClass and we have created it’s object and reference to that object is myClass. Than we started thread and from run method we called synchronized void method1().

     public synchronized void method1() {
        //thread has acquired object lock on object referenced by myClass ( by acquiring myClass’s monitor.)
      }

As soon as thread entered Synchronization method, thread acquired object lock on object referenced by myClass (by acquiring object’s monitor.)
Thread will leave lock when it exits synchronized method.



Now, let’s create a program >
class MyRunnable implements Runnable {
  
   public void run() {
          method1();
         
   }
  
   public synchronized void method1(){
          for(int i=0;i<5;i++){
                 System.out.println(i+" "+Thread.currentThread().getName()+" is executing");
                 try {
                       Thread.sleep(500);
                 } catch (InterruptedException e) {e.printStackTrace(); }
          }
   }
}
public class MyClass {
   public static void main(String args[]) throws Exception {
          MyRunnable obj = new MyRunnable();
          Thread t1 = new Thread(obj,"Thread-1");  //Thread-1 on obj.
          Thread t2 = new Thread(obj,"Thread-2"); //Thread-2 on obj.
          t1.start();
          t2.start();
   }
}
/*OUTPUT
0 Thread-1 is executing
1 Thread-1 is executing
2 Thread-1 is executing
3 Thread-1 is executing
4 Thread-1 is executing
0 Thread-2 is executing
1 Thread-2 is executing
2 Thread-2 is executing
3 Thread-2 is executing
4 Thread-2 is executing
*/
If we note output, Thread-1 entered synchronized method and acquired obj’s lock meanwhile Thread-2 kept on waiting for obj’s lock. And once Thread-1 completed Thread-2 acquired obj’s lock and started executing.


But, it may also happen that Thread-2 might enter synchronized block first and in that case output will be -

/*OUTPUT
0 Thread-2 is executing
1 Thread-2 is executing
2 Thread-2 is executing
3 Thread-2 is executing
4 Thread-2 is executing
0 Thread-1 is executing
1 Thread-1 is executing
2 Thread-1 is executing
3 Thread-1 is executing
4 Thread-1 is executing
*/
If we note output, Thread-2 entered synchronized method and acquired obj’s lock meanwhile Thread-1 kept on waiting for obj’s lock. And once Thread-2 completed Thread-1 acquired obj’s lock and started executing.






RELATED LINKS>


Object and class lock >

Acquiring lock on class, 2 Ways to acquire lock on class

Difference between object Lock and class Lock



Thread Pool, Thread local, Busy Spin >

Implement Thread pool in java

ThreadLocal in multithreading in java - methods and usage with program

Busy Spin - What is busy spin? Consumer Producer problem with busy spin and solution to busy spin.



Situation based questions -

Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time?

Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in static synchronized method1(), can Thread-2 enter static synchronized method2() at same time?


Interviews >

THREADS - Top 80 interview questions and answers (detailed explanation with programs) Set-1 >  Q1- Q60

THREADS - Top 80 interview questions and answers, important interview OUTPUT questions and answers, Set-2 > Q61- Q80





eEdit
Must read for you :