Is it really necessary to use the "monitor" object (java)

I've seen object monitors used in java a few times, but it seems to me that any object monitor logic can be easily replaced using synchronized code blocks and / or methods.

What is the purpose of using an explicit object monitor, and not just carefully coordinating synchronized blocks of code with Atomic primitives?


source to share

4 answers

There is always a monitor object. When you have a synchronized block, your class instance is a monitor object. So the reasons for using explicit objects are:

1) you can share them between class instances to synchronize access to a shared resource

2) more explicit

3) you can give your monitor object a useful name

4) more flexible



You make a distinction where none exists (or uses unusual terminology). In Java terms, a monitor is an object used as a parameter to a synchronized block (or, in the case of synchronous instance methods, implicitly an instance this

and with a synchronized static method an instance of a class).



The main thing is that a regular block synchronized

uses the environment object as its monitor, in other words, it is equivalent to using synchronized(this) { }

. The problem is scoping / visibility: any class external to your class can choose to sync in one instance and interfere with your sync logic. Using the link private final

as a monitor is no longer possible (assuming no shenanigans are involved).

It is formulated in the Java Concurrency In Practice as follows (p61, section 4.2.1):

There are advantages to using a private lock object instead of an inline object lock (or any other public lock). Creating a private lock object encapsulates the lock so that client code cannot acquire it, whereas a public lock allows client code to participate in its synchronization policy - right or wrong. Clients that improperly acquire another object can cause liveness issues, and validating the correct use of a shared lock requires examining the entire program, not just one class.



but it seems to me that any object monitor logic can be easily replaced using synchronized codeblocks and / or methods.

Yes, this is true for the same reason that a glass of water can be easily replaced with a glass of water - it's the same thing. Synchronized Java code blocks and methods render the monitor pattern at the language level.



All Articles