Sunday, 5 August 2018

Java when another new thread comes to synchronized block does it goes to wait state

In this post, I will discuss what happens when another new thread comes to synchronized block and what happens to its state.

Brief Introduction:

Lets start with understanding what is synchronized block. In Java, synchronized block is the set of code under curly brackets which can only be accessed by a thread holding lock of the object on which it is defined. For example

public class TestSynchronizedBlock {
 public void method1(){
  synchronized(this) {
   System.out.println("Inside synchronized block");
   // Do your stuff here
   System.out.println("Exiting synchronized block");
  }
 }
}


Consider the code above, in class TestSynchronizedBlock, inside method1 the synchronized block can be accessed by the thread who is holding lock for current object of TestSynchronizedBlock (as it is holding lock for this i.e. object of TestSynchronizedBlock class. Every Object (instance of class) in Java has one monitor lock (it is the part of Object class, thus is part of any class object) and the thread which first try to enter into synchronized block gets the monitor lock.

Conclusion:

As I said above, the thread which first try to enter into synchronized block has the exclusive monitor lock and it keeps the locks till the thread is executing inside the block. So if Thread A is executing inside synchronized block, what happens when Thread B try to execute. Thread B will go to wait state (waiting for lock) and it will release any other monitor lock it holds, if any. After Thread A will complete executing the synchronized block, it will release the lock and Thread B will get notified and will hold the monitor lock and then start executing (means it will come out of wait state and goes to Execution state). This holds true incase of multiple threads trying to acquire lock. It is worth to mention that If there is more than one thread waiting for lock and in wait state, after current thread completes the execution, only one thread out of waiting n thread will get notified and there is no such sequence as which one with get notified. You can also refer Spin lock for deep dive on locking mechanism.

That's all for synchronized block in context of multiple threads and its status. If you have any query / doubt / suggestion, please drop a comment.

No comments:

Post a comment