Member-only story

Java Multithreading, Concurrency, and Parallelism — Part 8

KRISHNA KISHORE V
6 min readDec 13, 2021

--

Synchronized and the depths of it — The monitors

NOTE: Dear Readers, please follow the content till the end as I tried to explain the things at the bytecode level as this is the core of multithreading in Java. If this is understood most of the java multithreading will be a cake walk for the reader.

In Part-7 we have seen how we can make a class thread-safe using synchronized keyword. We will now have an in-depth understanding of it by looking at the bytecodes.

The first thing to understand is that when the synchronized method or block gets executed, a lock is acquired. We generally say the lock is acquired on a resource. But what is that resource? In Java, that resource is always an Object — A Java Object.

In many books and articles, this lock is called an Intrinsic Lock, because the lock is acquired intrinsically without specifying (that the lock needs to be acquired). In the JVM vocabulary, it is called as the Monitor. Every object in Java has a monitor associated with it. In other words every Object in Java has a lock associated with it.

So now the question again is on which object the lock is acquired? There are two answers to this question.

First, if we are using synchronized method, the lock is always acquired on the object that is calling the synchronized method — this

Second, if we are using synchronized block, we have to specify the object on which…

--

--

KRISHNA KISHORE V
KRISHNA KISHORE V

Written by KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer

No responses yet

Write a response