Java Concurrency programming: synchronizing containers

Source: Internet
Author: User

Java Concurrency programming: synchronizing containers

To facilitate the writing of thread-safe programs, Java provides threading and concurrency tools such as synchronization containers, concurrent containers, blocking queues, synchronizer (such as Countdownlatch). Today we are going to discuss the synchronization container.

The following is the directory outline for this article:

I. Why are synchronization containers present?

Two. Synchronization container classes in Java

Three. Defects in the synchronization container

If there are any shortcomings please understand, and welcome criticism.

Please respect the author's labor results, reproduced please indicate the original link:

Http://www.cnblogs.com/dolphin0520/p/3932901.html

I. Why are synchronization containers present?

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, respectively, the three categories of containers, the Code array, the collection, and the queue.

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) is also the first 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:

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.currenttimemillis (); System.out.println ("ArrayList takes 100,000 Insertions:" + (End-start) + "MS"); start = System.currenttimemillis (); for (int i=0;i <100000;i++) Vector.add (i); end = System.currenttimemillis (); System.out.println ("Vector is time-consuming to insert 100,000 times:" + (End-start) + "MS");}}

The result of this piece of code running on my machine is:

  

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.

So in order to solve the performance problem of the synchronization container, a concurrent container is provided in Java 1.5, and the knowledge of concurrent containers in the Java.util.concurrent directory is described in the next article.

2. Is the synchronization container really 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:

public class Test {static vector<integer> Vector = new vector<integer> ();p ublic 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++) Vector.get (i);};}; Thread1.start (); Thread2.start (); while (Thread.activecount () >10) {}}}}

The result of running on my machine:

  

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

Maybe a friend will ask: vector is thread-safe, why do you still 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:

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

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

Then another thread executes the sentence:

for (int i=0;i<vector.size (); i++) 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:

public class Test {static vector<integer> Vector = new vector<integer> ();p ublic 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) {   //) 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) {}}}}

Resources:

"In-depth understanding of Java virtual machines"

"Java Concurrency Programming"

http://thinkgeek.diandian.com/post/2012-03-24/17905694

http://blog.csdn.net/cutesource/article/details/5780740

Java Concurrency programming: 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.