Java Concurrency (5): Synchronizing containers

Source: Internet
Author: User
Tags concurrentmodificationexception

I. Why the synchronization container appears

In the Java Collection Container framework, there are four main categories: list, Set, Queue, Map.

The List, Set, and queue interfaces inherit the collection interface respectively, and map itself is an interface.

Note that collection and map are a top-level interface, while list, set, and queue inherit the collection interface, which represents the three main classes of containers, arrays, sets, and queues.

Like ArrayList, LinkedList are implemented the list interface, HashSet implements the set interface, and Deque (two-way queue, allowing the team first, the team tail to join and out of the team) inherited the queue interface, Priorityqueue implements the queue interface. Another linkedlist (actually a doubly linked list) implements the Deque interface.

Containers such as ArrayList, LinkedList, and HashMap are non-thread-safe.

If there are multiple threads accessing these containers concurrently, the problem occurs.

Therefore, when you write a program, you must require programmers to manually synchronize with any access to those containers, which makes it extremely inconvenient to use these containers.

Therefore, Java provides a synchronization container for the user to use.

Two. Synchronization container classes in Java

In Java, the synchronization container mainly consists of 2 classes:

1) Vector, Stack, HashTable

2) class created by the static factory method provided in the collections class

Vector implements the list interface, vector is actually an array, and ArrayList similar, but the vector method is the synchronized method, that is, the synchronization measures.

The stack is also a synchronization container, and its methods are synchronized with synchronized, which is actually inherited from the vector class.

Hashtable implements the map interface, which is similar to HashMap, but Hashtable is synchronized and HashMap not.

The Collections class is a tool-providing class, note that unlike collection, collection is a top-level interface. A number of methods are provided in the collections class, such as sorting, finding, and so on for a collection or a container. Most importantly, it provides several static factory methods to create the synchronization container class, as shown in:

Three. Defects in the synchronization container

From the specific implementation of the synchronization container source, the method used in the synchronization container synchronized synchronization, it is obvious that this will inevitably affect the performance of execution, in addition, the synchronization container must be really completely thread-safe? Not necessarily, this will be mentioned below.

Let's take a look at the performance differences between traditional non-synchronous containers and synchronous containers, with ArrayList and vectors as an example:

1. Performance issues

Let's take a look at the differences in the performance of vectors and ArrayList when inserting data:

1  Public classTest {2      Public Static voidMain (string[] args)throwsinterruptedexception {3arraylist<integer> list =NewArraylist<integer>();4vector<integer> vector =NewVector<integer>();5         LongStart =System.currenttimemillis ();6          for(inti=0;i<100000;i++)7 List.add (i);8         LongEnd =System.currenttimemillis ();9System.out.println ("ArrayList 100,000 insert operation time:" + (End-start) + "MS");TenStart =System.currenttimemillis (); One          for(inti=0;i<100000;i++) A Vector.add (i); -End =System.currenttimemillis (); -System.out.println ("Vector 100,000 insert operation time:" + (End-start) + "MS"); the     } -}

The result of this piece of code is:

ArrayList 100,000 insert operation time: 8msVector 100,000 insert operation time: 17ms

With the same number of insertions, the vector takes twice times as much time as ArrayList. This is just one aspect of the performance issue on the reflection.

In addition, since both the Add method and the Get method are synchronized in the vector, when there are multiple threads accessing, if multiple threads are simply reading, then only one thread can read at a time, and the other threads can only wait, and the threads must compete for the same lock. Therefore, in order to solve the performance problem of the synchronization container, a concurrent container is provided in Java 1.5, located in the Java.util.concurrent directory.

2. Synchronizing containers is not necessarily safe

Some people think that the methods in the vector are synchronized, it must be thread-safe, in fact, this is not necessarily. Look at the following code:

1  Public classTest {2     Staticvector<integer> vector =NewVector<integer>();3      Public Static voidMain (string[] args)throwsinterruptedexception {4          while(true) {5              for(inti=0;i<10;i++)6 Vector.add (i);7Thread Thread1 =NewThread () {8                  Public voidrun () {9                      for(intI=0;i<vector.size (); i++)Ten Vector.remove (i); One                 }; A             }; -Thread thread2 =NewThread () { -                  Public voidrun () { the                      for(intI=0;i<vector.size (); i++) - Vector.get (i); -                 }; -             }; + Thread1.start (); - Thread2.start (); +              while(Thread.activecount () >10)   { A                   at             } -         } -     } -}

The result of the operation is:

As you can see, this code is an error: array subscript is out of bounds.

Some people may ask: vector is thread-safe, why do you report this error? Quite simply, for vectors, although it is guaranteed that only one thread can access it at any one time, it does not rule out the possibility that:

When a thread executes this sentence at some point:

1  for (int i=0;i<vector.size (); i++) 2     Vector.get (i);

If the vector's size method returns a value of 10,i of 9

Then another thread executes the sentence:

1  for (int i=0;i<vector.size (); i++) 2     Vector.remove (i);

The element with the subscript 9 is deleted.

Then accessing the element labeled 9 with the Get method will definitely be a problem.

Therefore, in order to ensure thread safety, additional synchronization measures must be made at the method call side, as shown below:

1  Public classTest {2     Staticvector<integer> vector =NewVector<integer>();3      Public Static voidMain (string[] args)throwsinterruptedexception {4          while(true) {5              for(inti=0;i<10;i++)6 Vector.add (i);7Thread Thread1 =NewThread () {8                  Public voidrun () {9                     synchronized(Test.class) {//For additional synchronizationTen                          for(intI=0;i<vector.size (); i++) One Vector.remove (i); A                     } -                 }; -             }; theThread thread2 =NewThread () { -                  Public voidrun () { -                     synchronized(Test.class) { -                          for(intI=0;i<vector.size (); i++) + Vector.get (i); -                     } +                 }; A             }; at Thread1.start (); - Thread2.start (); -              while(Thread.activecount () >10)   { -                   -             } -         } in     } -}
3. Concurrentmodificationexception exception

Concurrentmodificationexception exceptions are reported when iterative modifications are made to containers such as vectors, but this problem does not occur in concurrent containers. Refer to http://www.cnblogs.com/dolphin0520/p/3933551.html for this exception

Reference: Http://www.cnblogs.com/dolphin0520/p/3933404.html Haizi

Source:http://www.cnblogs.com/dolphin0520/ 

This blog does not indicate that the article reproduced by the author Haizi and the blog Park is shared, welcome reprint, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.

Java Concurrency (5): Synchronizing containers

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.