A reflection on Hashtable and hashmap caused by an anomaly

Source: Internet
Author: User
Tags reflection concurrentmodificationexception

For Hashtable and HashMap, believe that every person who learns Java is not unfamiliar, these two collections are not different in usage, but there is a big difference in the use of the environment:

(1) Differences, these two categories are mainly the following aspects of the difference:
Both Hashtable and HashMap implement the map interface, but the Hashtable implementation is based on the dictionary abstract class
In HashMap, NULL can be a key, with only one key, and a value of one or more keys to null.
When the Get () method returns a null value, you can either indicate that the key is not in HashMap or that the value of the key is null.
Therefore, it is not possible in HashMap to determine whether a key exists in the HashMap by the Get () method, but rather by using the ContainsKey () method.
In Hashtable, neither key nor value can be null.

The biggest differences between these two classes are:
(1) Hashtable is thread-safe, its methods are synchronized and can be used directly in a multithreaded environment.
(2) and HashMap is not thread-safe. In a multithreaded environment, the synchronization mechanism needs to be implemented manually.

The above is the interviewer is very keen to ask questions (of course, the level of the company will also ask a deeper, such as hashmap implementation mechanism), but this is not the focus of today.

I learn the Java language for many years, think of these two classes at my fingertips, but once into the process of the exception encountered, let me find myself to these two classes of understanding is not deep enough.

Some time ago, I use the Java language to implement a time scheduling algorithm, this algorithm is in my paper, the algorithm involves multiple threads, so I take it for granted Hashtable, but in the testing phase is frequently out of an anomaly, Concurrentmodificationexception, although quickly got a good solution, but this anomaly, so I have a deeper understanding of hashmap,hashtable,concurrenthashmap.

First, many people know that you should use Hashtable in multi-threaded situations, or you can synchronize HashMap with Synchronizedmap in collections. But the seemingly synchronized map still has potential thread-safety issues, consider one of the following scenarios

As in the following code:
Java code

<pre class= "java" name= "code" ><span style= "font-size:18px;" >//SHM is an instance of Synchronizedmap   
    if (Shm.containskey (' key ')) {   
        shm.remove (key);   
       }  
</span>


This code is used to determine whether this element exists before removing an element from the map. The ContainsKey and Reomve methods are synchronized, but the whole piece of code is not. Why. Assuming that thread a performs the ContainsKey method returns True, prepares to perform a remove operation, when another thread B begins execution, the same ContainsKey method returns True, and then the remove operation is performed And then thread A then performs the remove operation and finds that the element is not already there at this time. At this time will throw the above I encountered the exception concurrentmodificationexception, to ensure that this code according to our will work, one way is to the code to synchronize control, but the cost of doing so too much.

The exception that I encountered in my algorithm arises from the iterative process, and the code is as follows:

<span style= "FONT-SIZE:18PX;" > Iterator keys = Map.keyset (). iterator ();   
   while (Keys.hasnext ()) {   
        map.get (Keys.next ());   
      }  
  </span>

Encountered this anomaly when I also Baisibuxie, is clearly thread-safe how to produce this exception, the original keyset and iterator is a map of the elements of a "view", not "copy." That's where the problem is, when one thread is iterating over an element in the map, another thread may be modifying its elements. At this point, the concurrentmodificationexception exception may be thrown when the element is iterated.

Aware of the problem, it is much easier to solve, and finally I used the concurrenthashmap to do the replacement.

The CONCURRENTHASHMAP provides a different locking mechanism from the Hashtable and Synchronizedmap. The lock mechanism used in Hashtable is to lock the entire hash table at a time, so that it can only be operated by one thread at a time, while in concurrenthashmap it locks a bucket at a time.

Concurrenthashmap The hash table is divided into 16 buckets by default, and common operations such as Get,put,remove lock the bucket that is currently needed. This allows only one thread to enter, and now it can be executed with 16 write threads, and the elevation of concurrent performance is obvious.
In terms of iterations, Concurrenthashmap uses a different iterative approach.
In this iterative approach, when the iterator is created, the set is no longer thrown concurrentmodificationexception, instead, new data is changed so that it does not affect the original data. Replace the header pointer with the new data when the iterator is complete. This allows the iterator thread to use the original old data. Write threads can also be changed concurrently.

So far, the problem to solve, at the same time, for the set of multithreading has a new understanding, so after multithreading or using Concurrenthashmap better ...




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.