简体   繁体   中英

Is it ever truly necessary to use a “monitor” object (java)

Ive seen object monitors used in java several times, but it seems to me that any object monitor logic can easily be replaced by use of synchronized code blocks and/or methods.

What is the purpose for using an explicit object monitor rather than just carefully coordinating synchronized code blocks along with Atomic primitives ?

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

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

2) more explicit

3) you can give your monitor object a helpful name

4) more flexible

You're making a distinction where none exists (or are using uncommon terminology). In Java terms, a monitor is the object used as parameter to a synchronized block (or, in the case of synchronized instance methods, implicitly the this instance, and with synchronized static method the class instance).

The main thing is that a normal synchronized block uses the enclosing object as its monitor, in other words, it's equivalent to using synchronized(this) { } . The problem is one of scoping/visibility: any class external to your class can choose to synchronize on the same instance and interfere with your synchronization logic. By using a private final reference as the monitor, this is no longer possible (assuming no reflection shenanigans).

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

There are advantages to using a private lock object instead of an object's intrinsic lock (or any other publicly accessible lock). Making the lock object private encapsulates the lock so that client code cannot acquire it, whereas a publicly accessible lock allows client code to participate in its synchronization policy -- correctly or incorrectly. Clients that improperly acquire another object's lock could cause liveness problems, and verifying that a publicly accessible lock is properly used requires examining the entire program rather than a single class.

but it seems to me that any object monitor logic can easily be replaced by use of synchronized code blocks and/or methods.

Yes, this is true for the same reason that a glass of water can easily be replaced by a glass of water - they're the same thing. Java's synchronized code blocks and methods expose the monitor pattern at the language level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM