Following is an excerpt from JCIP
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.
Why can't we simply make the List< E > object private in the very first place to make the ListHelper class thread-safe?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With