Multi-threaded programming-immutable object mode of design mode

Source: Internet
Author: User
Tags visibility volatile

Immutable Object Design mode
Applicable scenarios:
1. The state of the modeled object changes infrequently: Set a dedicated thread to create a new immutable object when the state of the modeled object changes. Other threads simply read the state of the immutable object. A small trick in this scenario is that manipulator references to immutable objects are decorated with the volatile keyword, which avoids the use of display locks such as synchronize and the ability to ensure memory visibility between multiple threads.
2. Write operations on a set of related data at the same time, so it is necessary to ensure atomicity
In this scenario, in order to guarantee the atomicity of the operation, the usual practice is to use a display lock, but if the immutable object mode is used to combine this set of related data into an immutable object, then the operation of this set of data can be used without the display of locks to ensure atomicity, which simplifies the programming, It also improves the efficiency of code operation.
3. Use an object as the key of the HashMap: An object is placed into the hashmap as a key of the hashmap, and if the state of the object changes causing the hashcode to change, Will cause the same 1 object to be used as key to get to the associated value, although there is indeed an entry for the object as a key in the change HashMap. Conversely, because the state of an immutable object is not changed, its hashcode is not changed, which makes the immutable object very suitable for a key as a hashmap.

Design ideas:

Code design: The routing table relationship between the phone number prefix and the MMS Center routing table may change but the frequency of change is not high, and do not want to access the data lock and other concurrent access control, so as not to incur unnecessary overhead and problems.

Maintaining the routing table with immutable objects

Package com.immutableobject.design;

Import java.util.Collections;
Import Java.util.HashMap;
Import Java.util.Map;

/**
* MMS Center Routing Rules Manager
*
* @author Zhouhy
* @create 2017-09-29 11:03
*/

Public final class Mmscrouter {

Using volatile modifiers to ensure the visibility of the variable in multi-threaded environments
Private static volatile Mmscrouter instance = new Mmscrouter ();


Private final map<string,mmscinfo> Routemap;


Public Mmscrouter () {
Load data in the database into memory as map
This.routemap = Mmscrouter.retrieveroutemapfromdb ();
}

private static map<string,mmscinfo> Retrieveroutemapfromdb () {

map<string,mmscinfo> map = new hashmap<string,mmscinfo> ();
Isolate data from database to map
return map;
}


public static Mmscrouter getinstance () {

return instance;
}

/**
*
* Gets the MMS center information of the object according to the phone number prefix
* @param msisdnprefix
* @return
*/
Public Mmscinfo getmmsc (String msisdnprefix) {

Return Routemap.get (Msisdnprefix);

}

public static void Setinstance (Mmscrouter newinstance) {

instance = newinstance;
}

private static map<string,mmscinfo> deepcopy (map<string,mmscinfo> m) {


map<string,mmscinfo> result = new hashmap<> ();

For (String Key:m.keyset ()) {

Result.put (Key,new mmscinfo (M.get (key)));
}

return result;
}
Data that will change to be protected from replication
Public map<string,mmscinfo> Getroutemap () {
Defensive replication
Return Collections.unmodifiablemap (Deepcopy (Routemap));
}
}

To represent the MMS center data using immutable objects:

Package com.immutableobject.design;

/**
* Use immutable objects to express MMS Center information
*
* @author Zhouhy
* @create 2017-09-29 11:08
*/

Public final class Mmscinfo {

/**
* Device number
*/
Private final String deviceId;

/**
* MMS Center URL
*/
Private final String URL;

/**
* Maximum attachment size allowed for this MMS center
*/
private final int maxattachmentsizeinbytes;


Public Mmscinfo (String deviceid,string url,int maxattachmentsizeinbytes) {

This.deviceid = deviceId;
This.url = URL;
This.maxattachmentsizeinbytes = maxattachmentsizeinbytes;
}


Public Mmscinfo (Mmscinfo prototype) {
This.deviceid = Prototype.deviceid;
This.url = Prototype.url;
This.maxattachmentsizeinbytes = prototype.maxattachmentsizeinbytes;


}
Public String Getdeviceid () {
return deviceId;
}

Public String GetUrl () {
return URL;
}

public int getmaxattachmentsizeinbytes () {
return maxattachmentsizeinbytes;
}



}

Participant Instances Monitor routing table data changes:

Package com.immutableobject.design;

/**
* The class to be docked with the operation and maintenance center; manipulator
*
* @author Zhouhy
* @create 2017-09-29 11:23
*/

public class Omcagent extends Thread {


@Override
public void Run () {
Boolean istablemodificationmsg = false;
String updatetablename = null;
while (true) {
/**
* Read the message from the socket connected to the OMC and parse
* After parsing to the routing table update message, reset the Mmscinfo instance
*/
if (istablemodificationmsg) {

if ("Mmscinfo". Equals (Updatetablename)) {
Mmscrouter.setinstance (New Mmscrouter ());
}
}
}
}
}

Problem with Attention:
1. The state of the modeled object is changed more frequently:
Frequent creation of immutable objects increases garbage collection.
2. Defensive replication: If the immutable object itself contains some states that need to be exposed, and the corresponding fields themselves are mutable (such as HashMap), then returning these field methods requires a defensive copy to prevent external code from modifying its internal state.

Copyonwritearraylist: Immutable object mode applied for thread-safe traversal



Public boolean Add (E e) {
Final Reentrantlock lock = This.lock;
Lock.lock ();
try {
object[] elements = GetArray ();
int len = elements.length;
Copies the original array and, based on this, sets the last element of the array to the element to be added
object[] newelements = arrays.copyof (elements, Len + 1);
Newelements[len] = e;
SetArray (newelements);
return true;
} finally {
Lock.unlock ();
}
}

Multi-threaded programming-immutable object mode of design mode

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.