Client Side Lock

Below is an excerpt from JCIP

enter image description here

The author says that in order to make this code thread safe, we must use client-side locking.

For this approach to work, we must use the same lock that List uses, using a client-side lock or an external lock. Client-side locking entails the protection of client code that uses an X object using X lock to protect its own state. To use client-side locking, you need to know what X locking uses.

enter image description here

Why can't we just make List <E> closed in the very first place to make the ListHelper class thread safe?

+5
source share
3 answers

In this case, when each instance of ListHelper contains its own list, you can make this list private and simply synchronize with the ListHelper instance. I suppose this is a slightly constructed example to make a point with a minimal amount of code. IMO the name ListHelper would mean that I could pass in an external list that could be reused by multiple instances of ListHelper .

I would say that the fact is that this code as it is and without changing the visibility of list (it can break other code) is better to synchronize to list than the current instance of ListHelper .

+6
source

First we need to understand the purpose of the author. The author’s goal is to create a thread-safe List tool that is safe for all methods, including putifAbsent methods.

And ListHelper may also have some other methods as follows:

 public void addList(E x) { list.add(x); } public void removeList(E x) { list.remove(x); } 

If some thread calls removeList and the second thread calls addList and the third one calls putIfAbsent, then because they are different locks, an error occurs.

0
source

It states that if you use a synchronized list and want to add another thread-safe method, you must use the same lock. the goal here is to show that if you synchronize the helper in this class, but rely on other synchronization methods provided by this list (blocking the list instance, this will break the thread's security.

0
source

All Articles