Java concurrency Programming (iii) design of thread-safe class-instance closure

Source: Internet
Author: User

So far, we've covered some basic knowledge of thread safety and synchronization. However, we do not want to analyze every memory access to ensure it is thread-safe, but instead want to combine some existing thread-safe components into larger-scale components or programs. After that, we'll talk about some of the basic concepts of designing thread-safe classes and introducing some of the combined patterns.


I. Designing Thread-safe classes

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

1. Identify all variables that make up the state of the object

2. Find the invariant condition of constraint state variable

3, establish the object state of the concurrent access management policy

To parse the state of an object, start with the object's domain first. If all the fields in the object are basic types of variables, then these fields will form the entire state of the object. If other objects are referenced in the domain, the state of the object will contain the domain of the referenced object. For example, the state of LinkedList contains the state of all the node objects in the list.

The synchronization policy defines how to collaborate on state access operations without violating object invariant or posteriori conditions. The synchronization policy specifies how immutability, thread closures, and locking mechanisms can be combined to maintain thread security and which variables are protected by which locks.


1. Collect synchronization requirements

To ensure that a class is thread-safe, it is necessary to ensure that its invariant conditions are not compromised in the case of concurrent access. Both the object and the variable have a state space, which is all possible values. The smaller the state space, the easier it is to determine the state of the thread. The more you use a final type of domain, the more you can simplify the parsing of the possible state of the object.

Some immutable conditions are defined in many classes to determine whether the state is valid or invalid . For example, a long variable, whose state space is from Long.min_value to Long.max_value, or some number of tables, the value of a variable cannot be negative.

Similarly, there are some posteriori conditions in the operation to determine whether the state migration is valid. For example, the variable counter current value is 17, the next state can only be 18. When the next state needs to depend on the current state, this operation must make a composite operation. Not all hungry operations impose restrictions on state transitions. For example, when you update a variable that holds the current temperature, the state before the variable does not affect the result of the calculation.

Additional synchronization and encapsulation are required because the invariant conditions and the posterior conditions impose various constraints on state and state transitions. If some states are not valid, the underlying state variables must be encapsulated, or the client code may leave the object in an invalid state. If there is an invalid state transition in an operation, the operation must be atomic. In addition, if this constraint is not imposed in the class, the requirements of encapsulation or serialization can be relaxed, and more flexibility or performance is achieved.


2. Operation with Dependent state

The invariant condition and the posteriori condition of a class constrain what states and state transitions are valid on an object. Some of the object's methods also contain state-based prior conditions (precondition). For example, you cannot remove an element from an empty queue, and the queue must be in a "non-empty" state before the element is deleted. If a priori condition based on a state is included in an operation, then this operation becomes a dependent state operation.


3. Ownership of the state

In many cases, ownership and encapsulation are always interrelated: the object encapsulates the state it owns, and vice versa, which holds ownership of the state it encapsulates. The owner of the state variable determines what locking protocol is used to maintain the integrity of the variable state. Ownership implies control. However, if you publish a reference to a Mutable object, you no longer have exclusive control, which is "shared control" at most. Classes typically do not own objects that are passed in from a constructor or from a method, unless they are specifically designed to transfer ownership of the passed-in object.

A container class typically shows a form of ownership separation in which the container class has its own state, while the customer code owns the state of each object in the container.


Ii. Closure of instances

If an object is not thread-safe, there are several techniques to make it safe to use in multithreaded programs. You can also ensure that the object can be accessed only by a single thread ( thread closure ), or through a lock to protect all access to that object .

Encapsulation simplifies the implementation of thread-safe classes, providing an instance closure mechanism (Instance confinement), often referred to as "closed." When an object is enclosed in another object, all code paths that can access the encapsulated object are known. It is easier to parse the code than when the object can be accessed by the entire program. By combining a closed mechanism with an appropriate locking policy , you can ensure that non-thread-safe objects are used in a thread-safe manner.

Strength containment is one of the simplest ways to build a thread-safe class, and he also gives you more flexibility in the choice of lock strategies.

There are also many examples of thread closures in the Java Platform class Library, where the only purpose of some classes is to load a non-thread-safe class into a thread-safe class. Some basic container classes are not thread-safe, such as ArrayList and HashMap, but the class library provides wrapper factory methods (such as collections.sychronizedlist and similar methods). Makes these non-thread-safe classes safe to use in a multi-threaded environment. These factory methods use the "adorner" (Decorator) mode to place the container-like wind state in a synchronized wrapper object, and the wrapper can implement each method in the interface as a synchronous method and forward the call request to the underlying container object. As long as the wrapper object has a unique reference to the underlying easy object, it is thread-safe.


1. Java Monitor Mode

The Java monitor pattern can be derived from the thread closure principle and its logical inference. That is, all the mutable states of an object are encapsulated and protected by the object's own built-in lock.

Java monitor patterns are used in many classes, such as vectors and HashTable.

The Java monitor pattern is just a convention for writing code that, for any kind of lock object, can be used to protect the state of an object as long as it is used throughout the object. As Privatelock shows how to use a private lock to protect the state.

public class Privatelock {Private Final object myLock = new Object ();D ate date;void SomeMethod () {synchronized (MyLock) {//visit Ask or modify the status of Date}}}

There are many advantages to using a private lock object instead of an object's built-in lock.

A private lock object can encapsulate a lock so that the customer code cannot be locked , but the client code can access the lock through the public method so that it (correct or incorrect) participates in its synchronization policy. In addition, to verify that a public access lock is being used correctly in the program, you need to examine the entire program, not a single class, reducing the complexity of the validation .





Java concurrency Programming (iii) design of thread-safe class-instance closure

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.