Designing thread-safe classes

Design thread-safe classes:

In the process of designing a thread-safe class, you need to include the following three basic elements:

  • find out all the variables that make up the state of the object;
  • Find out the invariance conditions that constrain the state variables;
  • Establish a concurrent access management strategy for object state.

To analyze the state of an object, start with the object's domain. If all fields in an object are variables of primitive types, then these fields will constitute the entire state of the object. If an object's domain references other objects, the object's domain contains the referenced object's domain.

A synchronization strategy defines how to coordinate access operations to an object's state without violating its invariance and a posteriori conditions. The synchronization policy specifies how to combine immutability, thread closure and locking mechanisms to maintain thread safety, and also specifies which variables are protected by which locks.

Gather synchronization requirements:

Immutable conditions are defined in many classes to determine whether the state is valid or invalid. For example, for a variable of type long, its state space is Long.MIN_VALUE to Long.MAX_VALUE. But we have defined a class that has a counter of type long, there is a restriction on the variable of type long, that is, it cannot be a negative value.

Also, some a posteriori conditions are included in the operation to determine whether the state transition is valid. If the current value of the counter is 17, then the next state can only be 16 or 18. When the next state needs to depend on the current state, this operation must be a compound operation.

Additional synchronization and encapsulation are required because invariance and posterior conditions impose many constraints on states and state transitions.

Thread safety cannot be guaranteed without knowledge of the object's immutable conditions and posteriors. To meet various constraints, we need to rely on atomicity and encapsulation.

State-dependent actions:

The invariance and posterior conditions of the class constrain which states and state transitions are valid on the object. Some state-based priors are also included in the methods of some objects. For example an element cannot be removed from an empty queue. If an operation contains state-based priors, the operation is called a state-dependent operation.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325250549&siteId=291194637