Follow the examples to learn java multithreading 6-how to correctly publish thread-safe objects, java6-

Source: Internet
Author: User

Follow the examples to learn java multithreading 6-how to correctly publish thread-safe objects, java6-


Everything we mentioned above is only for the purpose of correctly releasing a thread-safe object.

I. Closed threads

This is easy to understand. If a variable changes its status in a thread, the variable must be thread-safe.

We often use stack closures and ThreadLocal classes.

There is a virtual machine stack in the memory zone during java runtime. Stack blocking refers to this stack, which is private to the thread and has the same lifecycle as the thread. The Virtual Machine stack describes the Memory Model of java method execution. When each method is executed, a stack frame is created to store local variables and the operand stack. The process of calling each method until the execution is completed corresponds to the process from the inbound stack to the outbound stack of a stack frame in the Virtual Machine stack.

Then, the local variables defined in the called method are closed in the stack. Such variables must be thread-safe as long as they are not referenced and published.

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 will not damage the sealing of the stack in any way. We also see that localList is a local object, and the reference of an object points to it, the reference is also executed in the closed thread. However, once the localList object is published, the closeness will be damaged. We cannot determine how to use other external methods.

ThreadLocal variables are rarely used in code, because their features reduce code reusability and introduce implicit coupling between classes. Therefore, you must be extremely careful when using them, we will not talk about its instances here.

2. immutable object

An unchangeable object has the following conditions.

After an object is created, its status cannot be modified.

All fields of an object are of the final type.

The object is created correctly.

In fact, we often use such an immutable object to initialize it at the startup of the program, and then use multiple threads for concurrent access. The most important thing here is to correctly create and initialize the object, therefore, it must be ensured that all objects cannot be escaped. The common practice is to enable concurrent access threads after all such variables are initialized. This 1.1 guarantee must be ensured.

Iii. Common Security release Modes

1: Initialize an object reference in the static initialization function.

public class MongoDBTools {protected Logger logger = LoggerFactory.getLogger(MongoDBTools.class);private MongoClient configClient;private DB configDB;private Map<String, MongoTemplate> shardMongoTemplateMap = new HashMap<String, MongoTemplate>();private MongoDBTools() {init();}private static class SingletionHolder {private static MongoDBTools appConfigTools = new MongoDBTools();}public static MongoDBTools getInstance() {return SingletionHolder.appConfigTools;}@SuppressWarnings("deprecation")public void init() {}}


The getInstance method is used to obtain the singleton object initialized by the static field.

2: Save the object reference to the volatile type domain or AtomicReferance object.

This method has many limitations and is generally only applicable to read-only sharing mode.

3: Save the object reference to the final type domain of a correctly constructed object.

This method is often used, but if it is a variable State object, the release must be handled through the lock.

Package com. uskytec. ubc. interf. webservice; import java. util. concurrent. ConcurrentHashMap;/*** @ author gaoxu **/public class ConcurrentHashMapInstance {static ConcurrentHashMap <?, ?> Chm = null;/** obtain the Global Object of ConcurrentHashMap * @ return */public synchronized static ConcurrentHashMap <?, ?> GetCHM () {if (chm = null) {chm = new ConcurrentHashMap <String, Boolean> () ;}return chm ;}}


The ConcurrentHashMap concurrent object provided by java can be used to achieve thread security sharing.
4: Save the object reference to a domain protected by the lock.

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 * @ param 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 object, so we release it using thread-safe sharing, all operations on it are provided using public interfaces.

After mastering these release policies, we can better write thread-safe shared objects and safely execute concurrent tasks.



Zookeeper

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.