Immutable object mode of Java multithreaded programming

Source: Internet
Author: User

In a multithreaded environment, in order to ensure the consistency of shared data, it is often necessary to lock the use of shared data, but the lock operation itself brings some overhead, which can be used to encapsulate the shared data using immutable objects, thus avoiding the lock operation.

1. Model Roles

Immutable objects mean that there is no method within the object to modify the object data, and if any data for the shared variable needs to be modified, the entire shared object needs to be constructed, and then the shared object is replaced as a whole, in such a way as to guarantee the consistency of the shared object data. The following is a class diagram of the immutable object design:

The following is a description of each role feature:

    • Immutableobject: The carrier of an immutable object. For data that requires consistent changes, it needs to be placed in an immutable object, and there are several points to note for non-mutable objects:
    • The properties of an immutable object must use a final decoration to prevent the property from being accidentally modified, and final also guarantees that the property has been initialized successfully when the object is constructed (the JVM may have only allocated reference space when the object is constructed, and the individual property values may not have been initialized);
    • The value of the property must be constructed uniformly in the constructor method, and the rest of the methods are simply the methods that are provided for querying each property;
    • For a mutable state of a reference-type property, such as a collection, when you get a property of that type, you must return a deep copy of the property to prevent the property value of the immutable object from being modified by the client;
    • Classes of immutable objects must use final adornments to prevent subclasses from modifying themselves or their methods;
    • Manipulator: The management class for the aggregation object (some cases may not be used). For the management of aggregation objects, there are two main parts: Query and modification. For the query of the aggregate object, it is only necessary to get the object in the Manipulator class according to certain rules, and for the modification of the aggregate object, we need to construct a complete aggregate object by the parameter first, then replace the reference of the saved aggregation object.
    • Client: Gets the clients app for the aggregation object.
2. Usage Scenarios

For non-mutable objects, there are three main usage scenarios:

    • Immutable objects can be used when a group of data changes infrequently. For the data access, because the immutable object's reference space does not change, so that any thread can maintain the same immutable object reference, which can reduce the memory consumption, but also guarantee the consistency of data access;
    • Immutable objects can be used when a set of data requires consistent update operations. The immutable object can guarantee the consistency of the whole set of data because it guarantees that the modification of any data is the substitution of the whole object. It is important to note that immutable objects should not be used if the group data changes more frequently, because it creates a large number of immutable objects, which increases the pressure on the JVM garbage collection. The specific situation should be based on the JVM can use memory size and the frequency of object updates to consider;
    • An immutable object can be used when an object is required as a key to a map. For map, its hashcode () method returns the reference address of the object by default, and for non-mutable objects, it does not change because its reference address is not changed, even if its hashcode () method is not overridden.
3. Using the example

A good example of an immutable object is the latitude and longitude of the address. The work of the company to deal with the business and housing related, which is a part of the need to deal with the location of the latitude and longitude information, here can use immutable objects, because the room latitude and longitude will not change basically, and its operation is mainly to query-based, and most importantly, The processing of latitude and longitude must be a simultaneous change in latitude and latitudinal, and in any case only one of the data changes will cause problems. Here are the classes that record the latitude and longitude of a listing:

 Public Final classLocation {Private Final LongIdPrivate FinalString latitude;Private FinalString longitude; PublicLocation (LongID, string latitude, string longitude) { This.ID= ID; This.Latitude= Latitude; This.Longitude= Longitude; } Public Long getId() {returnId } PublicStringGetlatitude() {returnLatitude } PublicStringGetlongitude() {returnlongitude; }}

The location class is also the immutableobject part of the UML class diagram above. As you can see, any modifications to the Location object must be rebuilt with a location object. The following is the management class for location, which is used to store specific location information:

 Public classLocationholder {Private FinalLocationholder INSTANCE =New Locationholder();PrivateMap<long, location> locations;Private Locationholder() { This.Locations=NewConcurrenthashmap<> (); } PublicLocationholdergetinstance() {returnINSTANCE; } PublicLocationgetLocation(LongID) {returnLocations.Get(ID); } Public void addlocation(LongID, string latitude, string longitude) {Location location =NewLocation (ID, latitude, longitude); Locations.put(ID, location); } PublicMap<long, location>getlocations() {returnCollections.Unmodifiablemap(locations); }}

As you can see, the management of the location is done by a singleton class Locationholder, and any operation of the location is encapsulated, and the location is retrieved in bulk, and an immutable map is returned. This ensures that the original data will not be modified, and if either of the keys or values of the map may change, then the return value must return a deep copy of the result to guarantee the integrity of the original data.

Immutable object mode for multithreaded programming of Java

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.