Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

java - Why use private lock over intrinsic lock?

While reading about synchronization, I came across "monitor pattern" to encapsulate mutable states.

The following is the sample code

   public class MonitorLock {
      private final Object myLock = new Object();
      Widget widget;
      void someMethod() {
        synchronized(myLock) {
         // Access or modify the state of widget
        }
    }

}

Is it better in any way to have a private lock instead of the intrinsic lock?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes - it means you can see all the code which could possibly acquire that lock (leaving aside the possibility of reflection).

If you lock on this (which is what I assume you're referring to by "the intrinsic lock") then other code can do:

MonitorLock foo = new MonitorLock();
synchronized(foo) {
    // Do some stuff
}

This code may be a long way away from MonitorLock itself, and may call other methods which in turn take out monitors. It's easy to get into deadlock territory here, because you can't easily see what's going to acquire which locks.

With a "private" lock, you can easily see every piece of code which acquires that lock, because it's all within MonitorLock. It's therefore easier to reason about that lock.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...