Java high concurrency programming (III), java concurrent programming

Source: Internet
Author: User

Java high concurrency programming (III), java concurrent programming
Directory:

1. Several implementation methods of thread security Singleton Mode

2. Synchronize containers

3. Concurrent containers

I. Several implementation methods of thread security Singleton Mode

1. Hungry Chinese style (synchronization lock is not used, and the typical space is used for time)

public class Singleton1 {     private static Singleton1 mySingleton = new Singleton1();    private Singleton1(){         System.out.println("single");    }         public static Singleton1 getSingle(){        return mySingleton;    }    public static void main(String[] args) {        Thread[] ths = new Thread[200];        for(int i=0; i<ths.length; i++) {            ths[i] = new Thread(()->{                Singleton1.getSingle();            });        }                Arrays.asList(ths).forEach(o->o.start());    }} 

Running result:

2. Lazy (synchronization lock, delayed loading, and typical time-space change)

Public class Singleton2 {private static Singleton2 mySingleton; private Singleton2 () {System. out. println ("single");} public static synchronized Singleton2 getSingle () {// synchronize the method for obtaining the instance if (mySingleton = null) mySingleton = new Singleton2 (); return mySingleton;} public static void main (String [] args) {Thread [] ths = new Thread [200]; for (int I = 0; I <ths. length; I ++) {ths [I] = new Thread ()-> {Singleton2.getSingle () ;}) ;} Arrays. asList (ths ). forEach (o-> o. start ());}}

Running result:

3. Dual synchronization lock (reduced granularity and Dual Check)

Public class Singleton3 {private volatile static Singleton3 mySingleton; private Singleton3 () {System. out. println ("single");} public static Singleton3 getSingle () {// synchronize the methods used to obtain the instance if (mySingleton = null) {synchronized (Singleton3.class) {if (mySingleton = null) mySingleton = new Singleton3 () ;}return mySingleton;} public static void main (String [] args) {Thread [] ths = new Thread [200]; for (int I = 0; I <ths. length; I ++) {ths [I] = new Thread ()-> {Singleton3.getSingle () ;}) ;} Arrays. asList (ths ). forEach (o-> o. start ());}}

Running result:

Add the volatile keyword to mySingleton to ensure that the relationship (happens-before relationship) can occur first, so that all write operations are prior to the read operation, avoid seeing one half of mySingleton initialization in another thread, and the efficiency of double synchronization lock is also high.

4. Use the singleton mode of internal classes (neither locking nor lazy loading)

public class Singleton4 {        private Singleton4() {        System.out.println("single");    }        private static class Inner {        private static Singleton4 mySingleton = new Singleton4();    }        public static Singleton4 getSingle() {        return Inner.mySingleton;    }        public static void main(String[] args) {        Thread[] ths = new Thread[200];        for(int i=0; i<ths.length; i++) {            ths[i] = new Thread(()->{                Singleton4.getSingle();            });        }                Arrays.asList(ths).forEach(o->o.start());    }    }

Running result:

2. Synchronize containers

1. vector, stack, and hashtable ensure the atomicity of the method.

2. The small example program demonstrates the synchronization container

/*** There are N train tickets, each ticket has a serial number * with 10 window tickets * please write a simulation program ** to analyze what problems may occur in the following program? * Repeated sales? Excessive sales? **/Package yxxy. c_024; import java. util. arrayList; import java. util. list; public class TicketSeller1 {static List <String> tickets = new ArrayList <> (); static {for (int I = 0; I <10000; I ++) tickets. add ("Ticket No.:" + I);} public static void main (String [] args) {for (int I = 0; I <10; I ++) {new Thread ()-> {while (tickets. size ()> 0) {System. out. println ("sold --" + tickets. remove (0 ));}}). start ();}}}

Running result:

An out-of-the-boundary occurs, indicating that excessive sales and repeated sales have occurred.

The following uses a synchronous container and uses vector as an example to perform the ticket sales operation.

/*** There are N train tickets, each ticket has a serial number * with 10 window tickets * please write a simulation program ** to analyze what problems may occur in the following program? ** Use Vector or Collections. synchronizedXXX * for analysis. Can this solve the problem? **/Package yxxy. c_024; import java. util. vector; import java. util. concurrent. timeUnit; public class TicketSeller2 {static Vector <String> tickets = new Vector <> (); static {for (int I = 0; I <1000; I ++) tickets. add ("Ticket No.:" + I);} public static void main (String [] args) {for (int I = 0; I <10; I ++) {new Thread ()-> {while (tickets. size ()> 0) {/* try {TimeUnit. MILLISECONDS. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();} */System. out. println ("sold --" + tickets. remove (0 ));}}). start ();}}}

Running result:

...

According to the running results, the synchronization container seems to have achieved what we want, but there are still some problems.

When we use a synchronous container, although the container method is atomic, when we judge the separation from the operation, the middle part may still be interrupted by other threads, next we will simulate other logic between the judgment and the removal.

/*** There are N train tickets, each ticket has a serial number * with 10 window tickets * please write a simulation program ** to analyze what problems may occur in the following program? ** Use Vector or Collections. synchronizedXXX * for analysis. Can this solve the problem? **/Package yxxy. c_024; import java. util. vector; import java. util. concurrent. timeUnit; public class TicketSeller2 {static Vector <String> tickets = new Vector <> (); static {for (int I = 0; I <1000; I ++) tickets. add ("Ticket No.:" + I);} public static void main (String [] args) {for (int I = 0; I <10; I ++) {new Thread ()-> {while (tickets. size ()> 0) {try {TimeUnit. MILLISECONDS. sleep (10);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("sold --" + tickets. remove (0 ));}}). start ();}}}

Running result:

We can see that the program has an error, so although the synchronization container ensures the atomicity of the method, the judgment and operation may be separated, and the overall operation is not atomic.

 

3. Concurrent containers

1. Concurrent containers support multithreading

ConcurrentSkipListMap: The Skip table structure. It is a sorted container that performs the insert operation quickly.

ConcurrentHashMap divides the container into 16 segments. During each insert operation, only one segment is executed, and HashTable locks the entire segment.

Concurrent1_queue unbounded queue. If the memory consumption is not enough, you can always add (offer, add), take (poll out to delete, peek out to do not delete)

BolckingQueue blocking queue, add (put will wait if it is full), take (take will wait if it is empty)

Several special blocking Queues:

1) TransferQueue transfer queue. Compared with other queues, a transfer method producer sends the task directly to the consumer without entering the end queue. It is blocked when the transfer cannot find the consumer, real-time processing is usually used, and the queue has a certain capacity.

2) DelayQueue timing task queue

3) synchronusQueue: synchronization queue. For special transferQueue, there is no capacity queue. You cannot call the add method. You can only call the put Method to block waiting for consumption by the consumer. The tasks produced by the producer are directly consumed by the consumer.

Or the previous ticket sales program. Now we use a concurrent container to reexperiment with concurrent1_queue.

/*** There are N train tickets, each with a serial number * at the same time there are 10 window tickets for external sales * please write a simulation program ** use ConcurrentQueue to improve concurrency */package yxxy. c_024; import java. util. queue; import java. util. concurrent. concurrent1_queue; import java. util. concurrent. timeUnit; public class TicketSeller4 {static Queue <String> tickets = new concurrent1_queue <> (); static {for (int I = 0; I <1000; I ++) tickets. add ("Ticket No.:" + I);} public static void main (String [] args) {for (int I = 0; I <10; I ++) {new Thread ()-> {while (true) {String s = tickets. poll (); if (s = null) break; else System. out. println ("sold --" + s );}}). start ();}}}

Running result:

When we use the concurrent container concurrent1_queue, we call the poll method to sell tickets until the number of votes is 0, the string s will become null, so after the next if judgment, it will jump out

When we use concurrent containers in this example, it is highly efficient and will not cause problems.

4. Other common synchronization containers

1. Collocations. synchronizedXXX () locks unlocked containers. This method can be used in the case of low concurrency. concurrentSkipListMap can be used in the case of high concurrency and sorting.

2. CopyOnWriteList: copying a chain table during writing without locking the table during reading. Therefore, the reading efficiency is high, but the writing efficiency is very low. application scenarios: when a large number of reading and writing operations are required

V. Summary

1. Use of map/set

Wireless Security Requirements: hashmap, treemap, and linkedhashmap

Low concurrency: hashtable, Collections. synchronizedXXX ()

High concurrency: concurrentHashMap and concurrentSkipListMap

2. list

Wireless route security requirements: ArrayList and route list

Low concurrency: Collections. synchronizedXXX ()

High concurrency: Queue

Concurrent1_queue

BlockingQueue

LinkedBQ

ArrayBQ

TransferQueue

SynchronusQueue

DelayQueue

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.