It is well known that synchronization is recommended on a final private object (vs. synchronizing on this or even a protected data member).
But what happens when I have multiple classes (modules) in my application that need to synchronize on a common object?
Is there a way to reconcile these two seemingly contradicting requirements?
To better explain, if I have a private data member of class Owner defined as:
private final Object $01pfo = new Object[0];
Then any method in Owner could simply use it:
protected void anyMethod() {
synchronized ($01pfo) {
// do your thing
}
}
But if I want to synchronize on $01pfo from a different class (say User), is my only option to make $01pfo protected or public?
protected final Object $01pfo = new Object[0];
Is there a better approach? or solution?
synchronized blocks are working well in case if they are not spread among several objects.
in case if you need to synchronize operations using single lock in several classes – it’s better to take a look at Lock implementations.
It will give you much more freedom in granularing access to resources in several threads