Turn: java multithreading -- synchronous container, java multithreading -- container

Source: Internet
Author: User
Tags concurrentmodificationexception

Turn: java multithreading -- synchronous container, java multithreading -- container

  • Java synchronization container

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 represents three types of containers: array, Set, and Queue. Containers such as ArrayList, rule list, And HashMap are non-thread-safe. 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.

  • Synchronous containers in java

  1) Vector, Stack, HashTable

Vector implements the List interface. The Vector is actually an array, which is similar to ArrayList. However, the methods in the Vector are all synchronized methods, that is, the synchronization measures are implemented.

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.

2) the class created by the static factory method provided in the Collections class:

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 synchronous container class.

  • Synchronization container Defects

According to the specific implementation source code of the synchronization container, synchronized is used for synchronization in the synchronous container. Obviously, this will inevitably affect the execution performance. In addition, the synchronization container is not necessarily completely thread-safe, and additional synchronization measures need to be added.

For example:

1 public class Test {2 static Vector <Integer> vector = new Vector <Integer> (); 3 public static void main (String [] args) throws InterruptedException {4 while (true) {5 for (int I = 0; I <10; I ++) 6 vector. add (I); 7 Thread thread1 = new Thread () {8 public void run () {9 for (int I = 0; I <vector. size (); I ++) 10 vector. remove (I); 11}; 12}; 13 Thread thread2 = new Thread () {14 public void run () {15 for (int I = 0; I <vector. size (); I ++) 16 vector. get (I); 17}; 18}; 19 thread1.start (); 20 thread2.start (); 21 while (Thread. activeCount ()> 10) {22 23} 24} 25} 26}View Code 1 public class Test {2 static Vector <Integer> vector = new Vector <Integer> (); 3 public static void main (String [] args) throws InterruptedException {4 while (true) {5 for (int I = 0; I <10; I ++) 6 vector. add (I); 7 Thread thread1 = new Thread () {8 public void run () {9 synchronized (Test. class) {// perform additional synchronization 10 for (int I = 0; I <vector. size (); I ++) 11 vector. remove (I); 12} 13}; 14}; 15 Thread thread2 = new Thread () {16 public void run () {17 synchronized (Test. class) {18 for (int I = 0; I <vector. size (); I ++) 19 vector. get (I); 20} 21}; 22}; 23 thread1.start (); 24 thread2.start (); 25 while (Thread. activeCount ()> 10) {26 27} 28} 29} 30}View Code
  • ConcurrentModificationException exception

  ConcurrentModificationException is reported when the container is modified concurrently.

 1 public class Test { 2     public static void main(String[] args)  { 3         ArrayList<Integer> list = new ArrayList<Integer>(); 4         list.add(2); 5         Iterator<Integer> iterator = list.iterator(); 6         while(iterator.hasNext()){ 7             Integer integer = iterator.next(); 8             if(integer==2) 9                 list.remove(integer);10         }11     }12 }

In this case, the ConcurrentModificationException is reported. we can locate the source code to view the exception.

1 private class Itr implements Iterator <E> {2 int cursor; // index of next element to return 3 int lastRet =-1; // index of last element returned; -1 if no such 4 int expectedModCount = modCount; 5 6 public boolean hasNext () {7 return cursor! = Size; 8} 9 10 @ SuppressWarnings ("unchecked") 11 public E next () {12 checkForComodification (); 13 int I = cursor; 14 if (I> = size) 15 throw new NoSuchElementException (); 16 Object [] elementData = ArrayList. this. elementData; 17 if (I> = elementData. length) 18 throw new ConcurrentModificationException (); 19 cursor = I + 1; 20 return (E) elementData [lastRet = I]; 21} 22 23 public void remove () {24 if (lastRe T <0) 25 throw new IllegalStateException (); 26 checkForComodification (); 27 28 try {29 ArrayList. this. remove (lastRet); 30 cursor = lastRet; 31 lastRet =-1; 32 expectedModCount = modCount; 33} catch (IndexOutOfBoundsException ex) {34 throw new ConcurrentModificationException (); 35} 36} 37 38 final void checkForComodification () {39 if (modCount! = ExpectedModCount) 40 throw new ConcurrentModificationException (); 41} 42}View Code

First, let's take a look at several member variables:

Cursor: indicates the index of the next element to be accessed. It can be seen from the specific implementation of the next () method.

LastRet: indicates the index of the last accessed element.

ExpectedModCount: the expected value of the number of ArrayList modifications. Its initial value is modCount.

ModCount is a member variable in the javasactlist class. This value indicates the number of changes to the List. You can view the add () and remove () Methods of ArrayList to find that each call to add () the method or the remove () method adds 1 to modCount.

Because of the modification of modCount, expectedModCount and modCount are not equal, that is, checkForComodification () causes an exception.

Solution:

1: in a single-threaded environment: iterator. remove ();

2: In a multi-threaded environment:

1) Use synchronized or Lock for synchronization during iterator iteration;

2) Replace ArrayList and Vector with the concurrent container CopyOnWriteArrayList.

  • Concurrent classes added in Java 5

As we all know, HashMap is non-thread-safe, and Hashtable is thread-safe. However, because Hashtable adopts synchronized for synchronization, it is equivalent to competing for a lock when all threads perform read and write operations, resulting in very low efficiency. ConcurrentHashMap can read data without locking, and its internal structure allows it to keep the granularity of the lock as small as possible during write operations without locking the entire ConcurrentHashMap.

The CopyOnWrite container is the container copied during writing. The general understanding is that when we add elements to a container, instead of directly adding elements to the current container, we first Copy the current container and Copy a new container, add elements to the new container. After adding the elements, point the reference of the original container to the new container. The advantage of doing so is that we can concurrently read the CopyOnWrite container without locking, because the current container does not add any elements. Therefore, the CopyOnWrite container is also an idea of read/write separation. The read and write containers are different.

The CopyOnWrite container has many advantages, but there are also two problems, that is, the memory usage and data consistency problems: the CopyOnWrite container can only ensure the final consistency of data, but cannot ensure the real-time consistency of data. Therefore, if you want to read the data you want to write, do not use the CopyOnWrite container.

Refer to blog:

Http://home.cnblogs.com/u/dolphin0520/

Related Article

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.