Member-only story
Java Multithreading, Concurrency, and Parallelism — Part 9
Synchronized on class objects and the scenarios of thread blockings
In Part-8 we have seen how the synchronized
keyword works and its two bytecodes the monitorenter
and monitorexit.
But we have seen in the context of instance methods. Now we will see what happens with static
methods.
NOTE: The words
lock
andmonitor
are used interchangeably here. Both are the same in our context.
With the static methods, the synchronization happens the same way except for the object on which the monitor is acquired. The lock/monitor is acquired on the class
object.
When we use synchronized
with the instance methods, the monitor is acquired on thethis
object and when used with static methods the lock is acquired on the .class
object.
Here is our Counter
class with static synchronized methods.
And here is the bytecode snapshot of increment()
method.