Question

When to use private lock object to synchronize a block?

Object lock =new Object();  
synchronized(lock)
{  }

When to use client side lock to synchronize a block?

private final List<InetAddress> ips =
Collections.synchronizedList(new ArrayList< InetAddress >());  
synchronized(ips)
{  }

Why client side lock is not preferred?

Was it helpful?

Solution

The object must be used explicitly for locking purposes in synchronized blocks within the class’s methods. This intrinsic lock is associated with the instance of the private object and not the class. Consequently, there is no lock contention between this class’s methods and the methods of a hostile class(as it is a good practice to declare the object locks as private and final).

In client-side locking the class holds a lock on an object that might be accessible to other classes. Client-side locking entails guarding client code that uses some object X with the lock X uses to guard its own state. In order to use client-side locking, you must know what lock X uses. client-side locking is even more fragile because it entails putting locking code for a class into classes that are totally unrelated to that particular class.

For instance,if a class A has methods which use method synchronization.Another class B has a reference to class A and uses the object of class A as the lock to synchronize blocks in a method. If someday the locking strategy of class A is modified to use a private final lock object,then class B's locking strategy breaks because threads that call the methods of class A will adhere to the new locking strategy whereas the methods in class B still use object of class A as the lock . Consequently, the implementation will use two different locks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top