Learn Java Multi-Threading 6 with instances-How to publish thread-safe objects correctly

Source: Internet
Author: User


All we've talked about is just a goal. That is, a thread-safe object can be published correctly.

One: Thread closure

Well, that's a good idea. If a variable is a state change done in a thread, then this variable is certainly thread-safe.

We often use stack closures and threadlocal classes.

In the Java Runtime Memory area there is a virtual machine stack, the stack closure is the stack, this stack is thread-private, its life cycle is the same as the thread. The virtual machine stack description describes the memory model that is executed by the Java method: When each method is executed, a stack frame is created to store the local variable, the operand stack, and so on. Each method is called until the completion of the process, corresponding to a stack frame in the virtual machine stack from the stack to the process of the stack.

Then the local variables that we define in the inside of the called method are enclosed in the stack, so that it must be thread safe so long as it does not publish a reference to the variable.

public int Getbadnum (list<string> paralist) {list<string> locallist;int num = 0;locallist = Paralist;for ( String t:locallist) {if ("bad". Equals (t)) {++num;}} return num;}

In this method, NUM does not destroy the enclosing of the stack anyway, we also see that locallist is a local object, the reference of an object points to it, and it is enclosed in the thread so that the reference is executed in the enclosing thread. However, once the Locallist object is published, the closure will be destroyed. We can't be sure how other external methods will use it.

The threadlocal variable is seldom used in our code, because its properties degrade the reusability of the code and introduce implicit coupling between classes, so be careful when using it, and we won't talk about its instances here.

Two: Immutable objects

Immutable objects have the following conditions.

The state cannot be modified after the object is created.

All fields of an object are final types.

The object is created correctly.

In fact, we often use such immutable objects at the start of the program to initialize it, and then multi-threaded concurrent access, the most critical here is to correctly create the object and initialize, so it must be guaranteed that all objects can not escape, it is common practice to initialize all such variables at the start of the concurrent access thread, This must be ensured.

Three: The common mode of security release

1: Initializes a reference to an object in the static initialization function.

public class Mongodbtools {protected Logger Logger = Loggerfactory.getlogger (mongodbtools.class);p rivate mongoclient Configclient;private DB configdb;private map<string, mongotemplate> shardmongotemplatemap = new HashMap< String, mongotemplate> ();p rivate mongodbtools () {init ();} private static class Singletionholder {private static Mongodbtools Appconfigtools = new Mongodbtools ();} public static Mongodbtools getinstance () {return singletionholder.appconfigtools;} @SuppressWarnings ("deprecation") public void init () {}}


What we get with the GetInstance method is that we use the static domain to initialize the singleton objects well.

2: Save the object's reference to a volatile type of field or to a Atomicreferance object.

This approach has great limitations and generally applies only to read-only shared mode.

3: Saves the object's reference to the final type field of a properly constructed object.

This is the way we often use but if the release of an object in a mutable state must be handled by a lock.

Package Com.uskytec.ubc.interf.webservice;import java.util.concurrent.concurrenthashmap;/** * @author gaoxu * */ public class Concurrenthashmapinstance {static concurrenthashmap<?,? >  chm = null;/** Get Concurrenthashmap Global Object * @return */public synchronized static concurrenthashmap<?,? > Getchm () {if (chm==null) { CHM = new concurrenthashmap<string, boolean> ();} return CHM;}}


Thread-safe sharing can be achieved with concurrenthashmap concurrency objects provided by Java.
4: Save the object's reference to a lock-protected domain.

Package Com.uskytec.ubc.foundation.queue;import java.util.hashmap;/** Route Cache * @author Gaoxu * */public class Routecache {private static Routecache instance = null;public synchronized static Routecache getinstance () {if (instance = = NULL) instance = new Routecache (); return instance;} Private final static hashmap<string,object> Routecache = new hashmap<string,object> ();/** * @param key * @para M value * @return */public synchronized int Add (String key,object value) {routecache.put (key, value); return 1;} /** * @param key * @return */public synchronized Object get (String key) {    if (routecache! = null)    return Routecache . get (key);    return null;}} The Routecache in the instance is a mutable state object, so we publish it in a thread-safe way, and operate on it with the public interface.

With these release strategies in hand, we can better write thread-safe shared objects and implement concurrent tasks safely.





Follow the example to learn Java multi-Threading 6-How to properly publish thread-safe objects

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.