Follow the example learning Java Multi-Threading 7-Object combination Publishing

Source: Internet
Author: User
Tags message queue

Our knowledge of thread safety and synchronization is to implement some reusable components or to write larger programs.

The class in Java is an object abstraction, so how to implement a thread-safe class is something we have to know and use correctly.

In the process of designing a thread-safe class, you need to include the following three basic elements:

Find all the variables that make up the state of the object.

Find the invariant condition of constraint state variable.

Establishes a concurrency access management policy for object state.

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 Illegalstate Exception ("counter Overflow"); return ++id;}}}

Method GetID is atomized, this is mainly because the state of the ID is a constraint condition, and this constraint determines the value of the ID of the validity, so it must be atomic processing of this step.

Instance closure

We are writing programs that use some non-thread-safe objects to store data, so that if the object is accessed or written in multiple threads, then it must be thread-safe, the best way is the closed processing in the thread. Let's look at an example that is often used:

package Com.uskytec.ubc.foundation.queue;import Java.util.linkedlist;import com.uskytec.ubc.foundation.entity.smssubmitentity;/** Save to SMS cat message Queue * @author Gaoxu * */public class Lnsentcache { private static Lnsentcache instance = null;public synchronized static Lnsentcache getinstance () {if (instance = = null) Insta nce = new Lnsentcache (); return instance;} Private final static linkedlist<smssubmitentity> Routecache = new linkedlist<smssubmitentity> ();/** * Add to specified buffer pool * @param type * @param smgpconfigid * @param submitmsg * @return */public synchronized int Add (smssubmitentity SM s) {Routecache.add (SMS); return 1;} /** * Gets the object of the specified buffer pool * @param sgipconfigid * @return */public Synchronized Object get () {if (Routecache! = Null&&r    Outecache.size () >0) return Routecache.removefirst (); return null;}} 

We use LinkedList to implement a FIFO queue, but LinkedList is not thread-safe, so we enclose it in an instance so that any thread can access its value.

Thread Safety Delegation

We often use concurrent objects such as Concurrenthashmap, which are Java-provided concurrency into objects, which implement synchronization mechanisms internally, so they are thread-safe, and we can delegate access to the unsafe object map entirely to it to entrust management, This way, with final type processing, we only need to implement the thread safety of the map through a shallow copy of the collections.

Examples we do not provide, you can go back to try to write, the next section we are discussing.

Implementing concurrent Add functionality with existing thread-safe classes

There are many such classes in the Java API, such as vectors, Hashtable, and so on, 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> () ;p ublic vector<iappraisewriterobserverservice> getobs () {return obs;}}


We use vectors to implement a listener list operation.

The synchronization class is a class that we often implement in practice, and we need to think more about the problem that my class needs to be written in thread-safe?



Follow the example learning Java Multi-Threading 7-Object combination Publishing

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.