The combination of 3--object of reading notes in Java concurrent programming combat

Source: Internet
Author: User

Want to combine some existing thread-safe components into larger-scale components or programs

Designing a thread-safe class

If all the fields in the object are primitive type variables, then these fields will form the entire state of the object. For example, the state of LinkedList includes the state of all the node objects in the list. To ensure thread security, you need to ensure that its invariant conditions are not compromised in the case of concurrent access.

Instance closure

When an object is encapsulated in another object, all code paths that can access the encapsulated object are known. 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. Closed objects must not exceed their established scope. Here's an example.

If the person class is mutable, additional synchronization is required when accessing the person object obtained from Personset. In the Java Platform Class Library There are many instances of thread closure, some of which are the only purpose of converting a non-thread-safe class into a thread-safe class. Some basic container classes are not thread-safe, such as ArrayList and hash, but the class library provides wrapper factory methods (such as collections.synchronizedlist and similar methods) so that these thread-unsafe classes can be used safely in multithreaded environments. These factory methods encapsulate the container class in a synchronous wrapper object through the adorner mode, and the wrapper can implement the methods in the interface as synchronous methods and forward the call request to the underlying container object. A wrapper object is thread-safe as long as it has a unique reference to the underlying container object.

Java Monitor mode

All mutable states are encapsulated and protected by the object's own built-in lock. Such as:

See the interesting part:

Using a private lock instead of an object's built-in lock (or any other publicly accessible lock) has many advantages. The private lock object can encapsulate the lock, and the customer code cannot get the lock, but the customer code can obtain the lock through the public method. This is the exact words of the book, but I don't understand. The first thing to figure out is the difference between a private lock and a built-in lock, and see a good blog post on the Web: http://www.jb51.net/article/56440.htm.

1. Class Lock: A static and synchronized lock is added to the method in the code, or a code snippet for synchronized (Xxx.class).

2. Object Lock: A synchronized lock is added to the method in the code, or a code snippet for synchronized (this).

3. Private Lock: Declare a private property within the class such as Private Object lock, which is required to lock the code snippet synchronized (lock).

4. Built-in Lock: Each Java object can be used as a lock that implements synchronization, and these locks become built-in locks. When a thread enters a synchronous code block or method, the lock is automatically acquired, and the lock is freed when the synchronization code block or method exits. The only way to get a built-in lock is to enter this lock's protected synchronous code block or method.

It seems that the built-in lock and object lock are one thing, but different angles define nature differently.

Example: Vehicle tracking

A "vehicle tracker" for dispatching vehicles, such as taxis, police cars, vans, etc. First Use monitor mode to build the vehicle tracker, and then try to loosen some of the encapsulation requirements while maintaining thread safety.

The thread that performs the update modifies the vehicle's location by data obtained from the GPS device or data entered by the dispatcher from the GUI interface.

The view thread and the thread that performs the update are accessing the data model concurrently, so the model must be thread-safe, and the following program gives a "vehicle tracker" based on the Java Monitor pattern implementation, which uses the mutablepoint in listing 4-5 to represent the vehicle's location.

Although class Mutablepoint are not thread-safe, the tracer classes are thread-safe. It contains both the map object and the Mutable Ponit object, and when it is necessary to return the location of the vehicle, copy the correct value by mutablepoint the copy constructor or Deepcopy method to generate a new map object. And the values in the object are the same as the key and value values in the original map object.

Thread-Safe delegation

Example: Delegate-based vehicle tracker

Constructs a vehicle tracker that is delegated to a thread-safe class. The location of the vehicle is saved to a map object, so a thread-safe map class Concurrenthashmap is implemented first. You can also use an immutable class point instead of Mutablepoint to save the location.

If you use the original Mutablepoint class instead of the point class, the encapsulation is broken because Getlocations publishes a reference to the mutable state. Here my understanding of the difference between the monitor mode and the delegate is that the monitor encapsulates all the mutable states, and the operations on those states are protected with built-in locks. The delegate mode is to delegate the security of these states to some thread-safe containers to protect. One more thing to note in the above code is that getlocations returns a non-modifiable but real-time view of the vehicle location.

Stand-alone state variables

Delegate the security of a thread to multiple state variables. As long as these variables are independent of each other.

When a delegate fails

There are certain invariance conditions between state variables, such as:

The delegation mechanism is not sufficient for thread safety at this time, and this class must provide its own locking mechanism.

Publish the underlying state variable

Example: Vehicle tracker for publishing status

Release the underlying mutable state in this release.

Adding functionality to existing thread-safe classes

In a nutshell, use the Security class library provided by Java and add our own classes to ensure thread safety for the program functionality we are implementing.

Client lock mechanism

Combination

When adding an atomic operation to an existing class, there is a better way to do this: combine.

Using the Java Monitor mode to encapsulate an existing list, you can ensure thread safety as long as you have a unique external reference to the underlying list in the class. (Note that the underlying list instance here is private and immutable)

Experience: The main content of this chapter is how to ensure thread safety when multiple objects are grouped together. Feel this chapter is really very abstract, said a lot of theoretical things, now still have a lot of unclear, do not understand the place, or rely on more practice to deepen understanding.

The combination of 3--object of reading notes in Java concurrent programming combat

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.