Why use a private padlock over a built-in lock?

While reading about synchronization, I came across a “monitor pattern” to encapsulate mutable states.

Below is a 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 to somehow have a private lock instead of a built-in lock?

+6
source share
1 answer

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

If you lock this (which I assume you are referring to is an "internal lock"), then other code might do:

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

This code may be far from MonitorLock itself and may call other methods, which in turn will output the monitors. It's easy to get stuck here because you cannot easily see what will gain locks.

With the "private" lock, you can easily see every piece of code that receives this lock, because all this is inside MonitorLock . Therefore, it is easier to talk about this lock.

+13
source

Source: https://habr.com/ru/post/897811/


All Articles