Java concurrent programming: Synchronous container

Source: Internet
Author: User

Java concurrent programming: Synchronous container
To facilitate coding of thread-safe programs, Java provides some thread-safe classes and concurrent tools, such as synchronous containers, concurrent containers, blocking queues, and Synchronizer (such as CountDownLatch ). Today we will discuss how to synchronize containers. The following is the directory outline of this article: 1. Why does the synchronization container appear? Ii. synchronous containers in Java III. Please forgive me for any errors caused by the defects of the synchronous containers, and you are welcome to criticize and correct them. 1. Why does the synchronization container appear? In Java's collection container framework, there are four main categories: List, Set, Queue, and Map. The List, Set, and Queue interfaces inherit the Collection interface, and Map itself is an interface. Note that Collection and Map are a top-level interface, while List, Set, and Queue inherit from the Collection interface, which contains three types of containers: Code array, Set, and Queue. For example, ArrayList and Queue List all implement the List interface. HashSet implements the Set interface, while Deque (two-way Queue, allowing the Queue to start and exit at the beginning and end of the Queue) inherits the Queue interface, priorityQueue implements the Queue interface. In addition, the sort list (which is actually a two-way linked list) is also the first Deque interface. Containers such as ArrayList, rule list, And HashMap are non-thread-safe. If multiple threads concurrently access these containers, the problem may occur. Therefore, when writing a program, you must require the programmer to manually synchronize the processing in any location that accesses these containers, which makes it very inconvenient to use these containers. Therefore, Java provides a synchronization container for your use. II. in Java, the synchronization container class mainly includes two types: 1) Vector, Stack, and HashTable 2) the class Vector created by the static factory method provided in the Collections class implements the List interface. The Vector is actually an array, similar to the ArrayList, but the methods in the Vector are all synchronized methods, that is, the synchronization is performed. Stack is also a synchronization container, and its method is also synchronized with synchronized, which actually inherits from the Vector class. HashTable implements the Map interface, which is similar to HashMap, but HashTable performs synchronous processing, while HashMap does not. Collections class is a tool-provided class. Note that unlike Collection, Collection is a top-level interface. A large number of methods are provided in the Collections class, such as sorting and searching Collections or containers. Most importantly, it provides several static factory methods to create a synchronization container class, as shown in figure 3. the defects of the synchronous container can be seen from the specific implementation source code of the synchronous container. If synchronized is used to synchronize the methods in the synchronous container, it is obvious that this will inevitably affect the execution performance. In addition, is synchronous containers truly completely thread-safe? Not necessarily. This will be discussed below. First, let's take a look at the performance differences between traditional non-synchronous containers and synchronous containers. We take ArrayList and Vector as examples: 1. for performance problems, let's take an example to see the performance difference between Vector and ArrayList when inserting data: public class Test {public static void main (String [] args) throws InterruptedException {ArrayList <Integer> list = new ArrayList <Integer> (); Vector <Integer> vector = new Vector <Integer> (); long start = System. currentTimeMillis (); for (int I = 0; I <100000; I ++) list. add (I); long end = System. currentTimeMil Lis (); System. out. println ("ArrayList 100000 insert operation time:" + (end-start) + "ms"); start = System. currentTimeMillis (); for (int I = 0; I <100000; I ++) vector. add (I); end = System. currentTimeMillis (); System. out. println ("it takes time for the Vector to perform 100000 insert operations:" + (end-start) + "ms") ;}} the result of this code running on my machine is: for the same number of insert operations, the time consumed by the Vector is twice that of the ArrayList. This is only a reflection of one aspect of performance issues. In addition, because the add and get methods in the Vector are synchronized, if multiple threads only perform read operations during access, at each moment, only one thread can read data, and other threads can only wait. These threads must compete for the same lock. Therefore, to solve the performance problem of synchronization containers, Java 1.5 provides concurrent containers located in the java. util. concurrent directory. The knowledge about concurrent containers will be described in the next article. 2. Is the synchronization container secure? Some people think that the methods in the Vector are all synchronized, so it must be thread-safe. In fact, this is not necessarily true. See the following code: public class Test {static Vector <Integer> vector = new Vector <Integer> (); public static void main (String [] args) throws InterruptedException {while (true) {for (int I = 0; I <10; I ++) vector. add (I); Thread thread1 = new Thread () {public void run () {for (int I = 0; I <vector. size (); I ++) vector. remove (I) ;};}; Thread thread2 = new Thread () {public void run () {for (int I = 0; I <vector. size (); I ++) vecto R. get (I) ;};}; thread1.start (); thread2.start (); while (Thread. result of activeCount ()> 10) {}}} running on my machine: As you can see, this code reports an error: the array subscript is out of bounds. Some may ask: why is this error reported when the Vector is thread-safe? It is very simple. Although Vector can ensure that only one thread can access it at a time point, it is not ruled out that when a thread executes this sentence at a time point: for (int I = 0; I <vector. size (); I ++) vector. get (I); If the size method of the vector returns 10, the value of I is 9, and the other thread executes this sentence: for (int I = 0; I <vector. size (); I ++) vector. remove (I); Delete the element whose subscript is 9. If you access an element with the subscript of 9 through the get method, a problem will occur. To ensure thread security, additional synchronization measures must be performed on the method caller, as shown in the following figure: public class Test {static Vector <Integer> vector = new Vector <Integer> (); public static void main (String [] args) throws InterruptedException {while (true) {for (int I = 0; I <10; I ++) vector. add (I); Thread thread1 = new Thread () {public void run () {synchronized (Test. class) {// perform additional synchronization for (int I = 0; I <vector. size (); I ++) vector. remove (I) ;};}; Thread thread2 = new Thread () {public void run () {synchronized (Test. class) {for (int I = 0; I <vector. size (); I ++) vector. get (I) ;};}; thread1.start (); thread2.start (); while (Thread. activeCount ()> 10 ){}}}

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.