Wednesday 4 December 2013

Intrinsic, Explicit and Client-Side Locking

Over the last some days, I have been reading about different locking mechanisms in Java and what interests me most about them is their so near-same yet different nature. Their differences are so subtle and delicate that it is not unusual to mistake one for the other. 

Intrinsic locking is based on locking upon the calling object or "this". When we simply append "synchronized" keyword to a method signature, what we are in fact implying is synchronized("this").

Explicit locking is relying on the lock used by the underlying private data member of the class. This encompasses delegation of thread safety to the class members,  and use of thread-safe members in the class such as ConcurrentHashMap, List and Vector.

Client-side locking relies on the lock employed by the class member itself. While, on first glance, this may seem exactly similar to explicit locks, it is a little different in essence. Explicit locks are used while performing mundane operations associated with the class object such as list.add(), list.removeAll() etc. Client-side locks are like wrappers over these collection objects that lock on the explicit lock associated with the object itself. Such a use case may be contemplated when you wish to perform operations with more than one data member of the class in a single atomic transaction. It relies on explicit locks of each of the concerned data members for manipulating them and uses its own wrapper design to encapsulate them in an atomic transaction. 

No comments:

Post a Comment