Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-side locking

Following is an excerpt from JCIP

enter image description here

The author says that in order to make the above code thread-safe we have to use client-side locking.

To make this approach work, we have to use the same lock that the List uses by using client-side locking or external locking. 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.

enter image description here

Why can't we simply make the List< E > object private in the very first place to make the ListHelper class thread-safe?

like image 360
prvn Avatar asked Sep 18 '15 11:09

prvn


1 Answers

In that case where each instance of ListHelper would contain its own list you could make that list private and just synchronize on the ListHelper instance. I guess this is a somewhat constructed example to make a point with as little code as possible. IMO the name ListHelper would imply that I could pass an external list which could clearly be reused by multiple ListHelper instances.

I'd say the point is: given the code as it is and without changing visibility of list (could break other code) you better synchronize on list than the current ListHelper instance.

like image 186
Thomas Avatar answered Sep 30 '22 06:09

Thomas