Chapter 2 describes how to construct a thread security class.
In the process of designing the thread security class, there must be three basic elements:
- Find all the variables that constitute the object state.
- Find out the immutability condition of the constraint state variable.
- Establishes a concurrent access management policy for the object status.
The commonly used techniques for constructing thread security classes are as follows:
When an object is encapsulated into another object, all code paths that can access the encapsulated object are known. Code analysis is easier than when the object can be accessed by the entire program. By combining the closed mechanism with the appropriate locking policy, we can ensure that non-thread-safe objects are used in thread-safe mode.
Objects can be enclosed in three places:
There are examples of multi-threaded closed class libraries on the Java platform. For example, some basic container classes are not thread-safe, such as ArrayList and HashMap. However, the Class Library provides the packaging factory method, these non-thread-safe classes can be safely used in a multi-threaded environment.
If a class is composed of multiple independent and thread-safe state variables and does not contain invalid state conversion in all operations, you can delegate thread security to the underlying state variables.
Add functions to the existing thread security class:
Example: if a thread-safe linked list is required, it must provide an atomic "put-if-Absent" operation.
1. Expansion
BetterVector<E> Vector<E> absent = ! }
The disadvantage of this method is that the current synchronization policy implementation is distributed to multiple separately maintained source code files, once the underlying class changes the synchronization policy and selects different locks to protect its state variables, the subclass will be destroyed, because the correct lock cannot be used to control concurrent access to the base class status after the synchronization policy is changed.
2. Client Lock Mechanism
ListHelper<E> List<E> list = Collections.synchronizedList( ArrayList<E> absent = ! }
This method is very fragile because it puts the lock code of class C into other classes that are completely independent of class C, which can lead to confusion.
The client locking mechanism and the extended class mechanism share the same thing: coupling the behavior of the derived class with the implementation of the base class, and the extension damages the encapsulation of the implementation, the locking of the client compromises the encapsulation of the synchronization policy.
3. Combination
ImprovedList<E> List<E> List<E> ImprovedList(List<E> .list = contains = ! }
The Java monitor mode is used to encapsulate the existing List. As long as the class has a unique external reference pointing to the underlying List, the thread security can be ensured.
At last, we need to document the synchronization policy.