What will imply with respect to optimizing Java code if I use list1 and list2 instead of lock1 and lock2?
It's not about optimization, it's about encapsulation.
In your example, there will be no practical difference between the synchronization of list objects and the synchronization on individual lock objects.
A common use case for a private lock object is when a class functions as a monitor. The classic monitor implementation looks like this:
class MyMonitor { synchronized foo(...) { ... } synchronized bar(...) { ... } synchronized baz(...) { ... } }
A private castle does the same thing as
class MyMonitor { private Object lock = new Object(); foo(...) { synchronized(lock) { ... } } bar(...) { synchronized(lock) { ... } } baz(...) { synchronized(lock) { ... } } }
The βproblemβ with the classic way is that a client of the MyMonitor class could potentially use an instance of MyMonitor to synchronize something else:
MyMonitor myMonitor = ...; synchronized( myMonitor ) { ... }
Why has anyone ever written this? I have no idea. But if someone did this, then client-side use of the myMonitor object as a lock can prevent the MyMonitor class from using the same object as the lock.
The second way to use a private lock object is to ensure that even if the client actually uses MyMonitor to lock something else, it cannot interfere with the private locking of the MyMonitor instance.
None of this applies to your example, because in your example, lists are private variables that are (presumably) not visible to clients.
source share