How does thread synchronization occurs inside a monitor? What levels of synchronization can you apply?What is the difference between synchronized method and synchronized block

  • In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword.
  • The synchronized keyword can be applied in method level (coarse grained lock – can affect performance adversely) or block level of code (fine grained lock).
  • Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method.
  • Since each object has a lock, dummy objects can be created to implement block level synchronization.
  • The block level is more efficient because it does not lock the whole method.
  • The JVM uses locks in conjunction with monitors.
  • A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code.
  • Each monitor is associated with an object reference.
  • When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object.
  • The thread is not allowed to execute the code until it obtains the lock.
  • Once it has obtained the lock, the thread enters the block of protected code.

 

  • When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. For static methods, you acquire a class level lock.