Java High concurrency Programming (iii)

Source: Internet
Author: User
Tags volatile ticket

Directory:

1. Several ways to implement thread-safe singleton mode

2. Synchronizing containers

3. Concurrent containers

One, a few ways to realize the thread-safe single case mode

1. A Hungry man type (no sync lock, typical space change time)

 Public classSingleton1 {Private StaticSingleton1 Mysingleton =NewSingleton1 (); PrivateSingleton1 () {System.out.println ("Single"); }          Public StaticSingleton1 Getsingle () {returnMysingleton; }     Public Static voidMain (string[] args) {thread[] ths=Newthread[200];  for(inti=0; i<ths.length; i++) {Ths[i]=NewThread ((){singleton1.getsingle ();        }); } arrays.aslist (THS). ForEach (o-O.start ()); }} 

Operation Result:

2. Lazy-type (use synchronous lock, delay loading, typical time to change space)

 Public classSingleton2 {Private StaticSingleton2 Mysingleton; PrivateSingleton2 () {System.out.println ("Single"); }              Public Static synchronizedSingleton2 Getsingle () {//to synchronize the method that gets the instance        if(Mysingleton = =NULL) Mysingleton=NewSingleton2 (); returnMysingleton; }         Public Static voidMain (string[] args) {thread[] ths=Newthread[200];  for(inti=0; i<ths.length; i++) {Ths[i]=NewThread ((){singleton2.getsingle ();        }); } arrays.aslist (THS). ForEach (o-O.start ()); }}  

Operation Result:

3. Double sync lock (reduced granularity, double check

 Public classSingleton3 {Private volatile StaticSingleton3 Mysingleton; PrivateSingleton3 () {System.out.println ("Single"); }             Public StaticSingleton3 Getsingle () {//to synchronize the method that gets the instance       if(Mysingleton = =NULL){           synchronized(Singleton3.class){               if(Mysingleton = =NULL) Mysingleton=NewSingleton3 (); }       }       returnMysingleton; }         Public Static voidMain (string[] args) {thread[] ths=Newthread[200];  for(inti=0; i<ths.length; i++) {Ths[i]=NewThread ((){singleton3.getsingle ();        }); } arrays.aslist (THS). ForEach (o-O.start ()); }}

Operation Result:

Add the volatile keyword to Mysingleton to ensure that the relationship (Happens-before relationship) is preceded, so that all writes occur before the read operation. Avoid seeing one half of the Mysingleton in another thread, while the double sync lock is also highly efficient

4. Use the singleton mode of the inner class (without locking or lazy loading)

 Public classSingleton4 {PrivateSingleton4 () {System.out.println ("Single"); }        Private Static classInner {Private StaticSingleton4 Mysingleton =NewSingleton4 (); }         Public StaticSingleton4 Getsingle () {returnInner.mysingleton; }         Public Static voidMain (string[] args) {thread[] ths=Newthread[200];  for(inti=0; i<ths.length; i++) {Ths[i]=NewThread ((){singleton4.getsingle ();        }); } arrays.aslist (THS). ForEach (o-O.start ()); }    }

Operation Result:

Second, the synchronous container

1.vector, Stack, Hashtable, etc., to ensure the atomic nature of the method

2. Small Example Program demo synchronization container

/*** There are n train tickets, each ticket has a number * at the same time, there are 10 windows ticketing * Please write a simulation program * * Analysis of the following programs may cause problems? * Repeat sales? Excess sales? *  */ Packageyxxy.c_024;Importjava.util.ArrayList;Importjava.util.List; Public classTicketSeller1 {StaticList<string> tickets =NewArraylist<>(); Static {         for(inti=0; i<10000; i++) Tickets.add ("Ticket Number:" +i); }                 Public Static voidMain (string[] args) { for(inti=0; i<10; i++) {            NewThread ((){                 while(Tickets.size () > 0) {System.out.println ("Sold--" + tickets.remove (0));        }}). Start (); }    }}

Operation Result:

There was a cross-border situation, indicating that excessive sales and repeated sales occurred

Use the synchronization container below, take vector as an example and do the ticket operation again.

/*** There are n train tickets, each ticket has a number * at the same time, there are 10 windows ticketing * Please write a simulation program * * Analysis of the following programs may cause problems? * Using vectors or collections.synchronizedxxx * To analyze, does this solve the problem? *  */ Packageyxxy.c_024;ImportJava.util.Vector;ImportJava.util.concurrent.TimeUnit; Public classTicketSeller2 {StaticVector<string> tickets =NewVector<>(); Static {         for(inti=0; i<1000; i++) Tickets.add ("Ticket Number:" +i); }         Public Static voidMain (string[] args) { for(inti=0; i<10; i++) {            NewThread ((){                 while(Tickets.size () > 0) {                                    /*try {TimeUnit.MILLISECONDS.sleep (10);                    } catch (Interruptedexception e) {e.printstacktrace (); }*/System.out.println ("Sold--" + tickets.remove (0));        }}). Start (); }    }}

Operation Result:

...

From the results of the operation, the synchronization container seems to have achieved what we want, but there are some problems

When we use a synchronous container, although the method of the container is atomic, but when the judgment and operation are separated, the middle part may be interrupted by other threads, let's simulate the other logic between the judgment and remove

/*** There are n train tickets, each ticket has a number * at the same time, there are 10 windows ticketing * Please write a simulation program * * Analysis of the following programs may cause problems? * Using vectors or collections.synchronizedxxx * To analyze, does this solve the problem? *  */ Packageyxxy.c_024;ImportJava.util.Vector;ImportJava.util.concurrent.TimeUnit; Public classTicketSeller2 {StaticVector<string> tickets =NewVector<>(); Static {         for(inti=0; i<1000; i++) Tickets.add ("Ticket Number:" +i); }         Public Static voidMain (string[] args) { for(inti=0; i<10; i++) {            NewThread ((){                 while(Tickets.size () > 0) {                                        Try{TimeUnit.MILLISECONDS.sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Sold--" + tickets.remove (0));        }}). Start (); }    }}

Operation Result:

We see an error in the program, so although the synchronization container guarantees the atomicity of the method, it may occur that the judgment is separated from the operation and the overall operation is not atomic

Third, concurrent containers

1. Concurrent Containers Support Multithreading

Concurrentskiplistmap Jump table structure, he is a well-ordered container to perform insert operations faster

Concurrenthashmap divides the container into 16 segments, executing only one of them each time the insert operation is performed, while the Hashtable is locked for an entire segment

Concurrentlinkedqueue unbounded queue, memory consumption can always add (Offer,add), take (poll take out the delete, peek out does not delete)

Bolckingqueue blocking queue, plus (put if full will wait), take (taking if empty will wait)

A few special blocking queues:

1) Transferqueue transfer queue, compared to other queues, more than one transfer method the producer sends the task directly to the consumer, does not enter the end queue, in the transfer cannot find the consumer situation to block, the real-time processing uses more, the queue also has a certain capacity

2) Delayqueue Timer task queue

3) Synchronusqueue synchronization queue, special Transferqueue, no capacity queue, can not call the Add method, can only call put method blocking waiting for consumer consumption, producer production tasks directly to consumer consumption

Or the previous ticketing procedure, now use concurrent containers to Concurrentlinkedqueue to re-experiment again

/*** There are n train tickets, each ticket has a number * at the same time there are 10 window tickets * Please write a simulation program * * Use Concurrentqueue to improve concurrency*/ Packageyxxy.c_024;ImportJava.util.Queue;ImportJava.util.concurrent.ConcurrentLinkedQueue;ImportJava.util.concurrent.TimeUnit; Public classTicketSeller4 {StaticQueue<string> tickets =NewConcurrentlinkedqueue<>(); Static {         for(inti=0; i<1000; i++) Tickets.add ("Ticket Number:" +i); }         Public Static voidMain (string[] args) { for(inti=0; i<10; i++) {            NewThread ((){                 while(true) {String s=Tickets.poll (); if(s = =NULL) Break; ElseSystem.out.println ("Sold--" +s);        }}). Start (); }    }}

Operation Result:

When we switch to concurrent container concurrentlinkedqueue, we call the poll method to ticket sales until the number of votes is 0 o'clock, the string s becomes null, so after the next if judgment will jump out

When we use concurrent containers in this example, it is highly efficient and does not have any problems

Iv. Other common synchronization containers

1.collocations.synchronizedxxx () Locks unlocked containers, which can be used when concurrency is not high, using concurrentskiplistmap when concurrency is high and needs to be sorted

2.CopyOnWriteList write-time copy of the linked table, no lock on the read, so the read time is high efficiency, but the writing efficiency is particularly low, the application scenario: in the need to read a large number of writes with

V. Summary

1. For the use of Map/set

Wireless Range Security Requirements: HashMap, TreeMap, Linkedhashmap

Low concurrency: Hashtable, collections.synchronizedxxx ()

High degree of concurrency: Concurrenthashmap, Concurrentskiplistmap

2.list

Wireless Range Security Requirements: ArrayList, LinkedList

Low concurrency: collections.synchronizedxxx ()

High degree of concurrency: Queue

Concurrentlinkedqueue

Blockingqueue

Linkedbq

Arraybq

Transferqueue

Synchronusqueue

Delayqueue

Java High concurrency Programming (iii)

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.