Why use private lock over intrinsic lock?

别等时光非礼了梦想. 提交于 2019-11-28 03:55:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7513227/why-use-private-lock-over-intrinsic-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!