Java Theory and Practice: Concurrent collection Classes

Source: Internet
Author: User
Tags mixed require wrapper concurrentmodificationexception

The first associated collection class that appears in the Java class Library is Hashtable, which is part of JDK 1.0. Hashtable provides an easy-to-use, thread-safe, associated map feature, which is of course convenient. However, thread safety is a cost-――hashtable all methods are synchronized. At this point, no competitive synchronization can result in considerable performance costs. Hashtable's successor, HashMap, appears as part of the set framework in JDK1.2, which solves thread-safety problems by providing an unsynchronized base class and a synchronized wrapper collections.synchronizedmap. By separating basic functionality from thread security, Collections.synchronizedmap allows users who need synchronization to have synchronization, and users who do not need to sync do not have to pay the price for synchronization.

There are two major deficiencies in the simple method of synchronizing Hashtable and Synchronizedmap (each method in a synchronized Hashtable or in a synchronized Map wrapper object). First, this approach is an obstacle to scalability because only one thread can access the hash table at a time. At the same time, this is still not enough to provide true thread security, and many common mixed operations still require additional synchronization. Although simple operations such as get () and put () can be done safely without additional synchronization, there are common sequences of operations, such as iterations or put-if-absent (empty), that require external synchronization to avoid data contention.

Conditional thread Security

The Synchronized collection wrapper Synchronizedmap and synchronizedlist, sometimes referred to as conditional ground security-all individual operations are thread-safe, but the sequence of operations consisting of multiple operations can cause data contention. Because the flow of control in the sequence of actions depends on the results of the preceding operation. The first fragment in Listing 1 shows the common put-if-absent statement block-If an entry is not in the MAP, add the entry. Unfortunately, when the ContainsKey () method returns to the time when the put () method is called, another thread might also insert a value with the same key. If you want to make sure that there is only one insertion, you need to wrap the pair of statements with a synchronized block that synchronizes with Map m.

The other examples in Listing 1 are related to iterations. In the first example, the result of List.size () may become invalid during the execution of the loop, because another thread can delete entries from this list. If the timing is not right, and an entry is deleted by another thread just after the last iteration of the Loop, List.get () returns NULL, and DoSomething () is likely to throw a NullPointerException exception. So what can be done to avoid such a situation? If another thread might be accessing the list when you are iterating over a list, you must use a synchronized block to wrap the list up and synchronize on List 1 to lock the entire list. This solves the data contention problem, but costs more in terms of concurrency, because locking the entire list during iterations blocks other threads, making it inaccessible to the list for a long period of time.

The collection framework introduces an iterator that iterates through a list or other collection, thus optimizing the process of iterating over elements in a collection. However, the iterator implemented in the Java.util collection class is extremely easy to crash, that is, if another thread is modifying the collection while one thread is traversing the collection through a iterator, then the next iterator.hasnext () or The Iterator.next () call throws a Concurrentmodificationexception exception. Just take this example, if you want to prevent concurrentmodificationexception exceptions, then when you are iterating, you must wrap the list with a synchronized block synchronized on List L to lock The entire List. (Alternatively, you can call List.toarray () to iterate over the array in a different step, but this is expensive if the list is larger).

Listing 1. Common competition conditions in a synchronized map

Map m = Collections.synchronizedMap(new HashMap());
  List l = Collections.synchronizedList(new ArrayList());
  // put-if-absent idiom -- contains a race condition
  // may require external synchronization
  if (!map.containsKey(key))
   map.put(key, value);
  // ad-hoc iteration -- contains race conditions
  // may require external synchronization
  for (int i=0; i<list.size(); i++) {
   doSomething(list.get(i));
  }
  // normal iteration -- can throw ConcurrentModificationException
  // may require external synchronization
  for (Iterator i=list.iterator(); i.hasNext(); ) {
   doSomething(i.next());
  }

The Illusion of trust

The conditional thread security provided by Synchronizedlist and Synchronizedmap also poses a risk-developers assume that because these collections are synchronized, they are thread-safe, so that they are negligent in the proper synchronization of mixed operations. The result is that while the surface of these programs works well at a lighter load, they start to throw nullpointerexception or concurrentmodificationexception once the load is heavy.

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.