Follow the examples to learn java multi-thread 7-object combination and release, java7-

Source: Internet
Author: User

Follow the examples to learn java multi-thread 7-object combination and release, java7-

The purpose of learning thread security and synchronization is to implement reusable components or compile larger programs.

Classes in java are object abstraction, so how to implement a thread security class is a technology we must know and use correctly.

In the process of designing the thread security class, there must be three basic elements:

Find all the variables that constitute the object state.

Find out the immutability condition of the constraint state variable.

Establishes a concurrent access management policy for the object status.

package com.home.thread.thread7;import com.home.thread.safe;public class Counter {/** * @author gaoxu *  */public class SafeThread {private int id = 0;@safepublic synchronized int getId(){if(id==Integer.MAX_VALUE)throw new IllegalStateException("counter overflow");return ++id;}}}

The getId method is atomic. Here, it is mainly because the id state judgment is a constraint, and this constraint determines the validity of the id value. Therefore, this step must be atomic.

Instance closed

Most programming programs use non-thread-safe objects to store data. If such objects are accessed or written by multiple threads, thread-safe processing is required, the best way is to close the processing in the thread. Let's look at a frequently used instance:

Package com. uskytec. ubc. foundation. queue; import java. util. using list; import com. uskytec. ubc. foundation. entity. smsSubmitEntity;/** queue for saving messages to the SMS cat * @ author GaoXu **/public class LNSentCache {private static LNSentCache instance = null; public synchronized static LNSentCache getInstance () {if (instance = null) instance = new LNSentCache (); return instance;} private final static Entity List <SmsSubmitEntity> r OuteCache = new parameter list <SmsSubmitEntity> (); /*** add to specified buffer pool * @ param type * @ param smgpConfigID * @ param submitMsg * @ return */public synchronized int add (SmsSubmitEntity sms) {routeCache. add (sms); return 1;}/*** get the Object of the specified buffer pool * @ param sgipConfigID * @ return */public synchronized Object get () {if (routeCache! = Null & routeCache. size ()> 0) return routeCache. removeFirst (); return null ;}}

We use the producer list to implement a first-in-first-out queue, but the producer list is not thread-safe, so we disable it for instances so that any thread can access its value.

Thread Security Delegation

We often use concurrent objects such as ConcurrentHashMap. They are the concurrency provided by java and become objects. they implement the synchronization mechanism internally, so they are thread-safe, we can entrust the access to the insecure object Map to it for management. In this way, we only need to implement thread security of Map through the shortest copy of Collections through final type processing.

We will not provide the instance first. You can go back and try to write it. We will discuss it in the next section.

Concurrent addition using existing thread-safe classes

Java APIs include many such classes, such as Vector and HashTable. Let's look at an example.

package com.gome.qiantai.tools;import java.util.Vector;import com.gome.qiantai.service.IAppraiseWriterObserverService;/** * @author gaoxu * */public class ObserverCache {private static ObserverCache instance = null;public synchronized  static ObserverCache getInstance(){if (instance == null)instance = new ObserverCache();return instance;}private static Vector<IAppraiseWriterObserverService> obs = new Vector<IAppraiseWriterObserverService>();public Vector<IAppraiseWriterObserverService> getObs(){return obs;}}


We use Vector to implement a listener list operation.

Synchronization classes are the classes we often implement in practice. We need to think more about this problem. Do my classes need to be written as thread-safe?



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.