Reusing an existing class instead of creating a new class can reduce effort, development risk, and maintenance costs.
Sometimes the thread-safe classes can support all of our operations, but more often, the existing classes can only support most of the operations, and you need to add a new operation without breaking the thread's security.
Here's an example: the need for a thread-safe linked list requires an atomic "Add (put-if-absent)" operation.
The Synchronized list class has implemented most of the functionality and can construct a "add if not" operation based on the Contains method and the Add method.
Modify the original class: unrealistic
Another way: Inherit this class, but inheritance is more vulnerable than adding the source code directly to the class, because the current synchronization policy implementation is distributed to multiple separately maintained sources. If the underlying class changes the synchronization policy and chooses a different lock to protect its state variables, the subclass is destroyed.
Client lock mechanism
The third approach: extending the functionality of the class, instead of inheriting the class itself directly, puts the extension code in a "helper class".
It is important to note that there is a difference between the lock of the helper class and the lock of the underlying object, and do not use the wrong lock. Otherwise the synchronous method appears to be locked, but in reality it is just an illusion, because using a different lock causes the underlying object to be modified by another thread (not the code path for the lock method of your helper Class).
For the method to execute correctly, the list must be locked in the implementation of the client or the external lock is used for the same lock.
Client-side locking means that for client code that uses an object x, the client code is secured by using the lock that the x itself uses to protect its state.
There's a situation?
Client-side locking is more vulnerable because it places the lock code for Class C in other classes that are completely unrelated to C.
Combination
The way that clients lock and inherit locking is fragile, and it is likely to be unsafe once someone does not follow the lock policy.
The combination method can add an extra lock with its own built-in lock without worrying about whether the underlying list is thread-safe.
Java Concurrency Programming (13) Adding functionality to existing thread-safe classes