简体   繁体   中英

What is the difference between Hashtable and HashMap if both throws ConcurrentModificationException in following code snippet?

In following code snippet, I tried with both Hashtable which is so called as thread safe and HashMap . But in both the cases I am getting ConcurrentModificationExceptionn . If this is so, then what is the advantages of HashTable over HashMap in case of thread safety

public class multiThreadedEnv {
    static Map<Integer, String> map = new Hashtable<Integer, String>();
    //static Map<Integer, String> map = new HashMap<Integer, String>();

    static{
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");
        map.put(4, "Four");
        map.put(5, "Five");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(){
            public void run() {
                Iterator itr= map.entrySet().iterator();
                while(itr.hasNext()){
                    Entry<String,String> entry=(Entry<String, String>) itr.next();
                    System.out.println(entry.getKey()+" , "+entry.getValue());
                    itr.remove();
                    Thread.sleep(2000);
                }
            }
        };

        Thread t2= new Thread(){
            public void run() {
                Iterator itr= map.entrySet().iterator();
                while(itr.hasNext()) {
                    Entry<String,String> entry=(Entry<String, String>) itr.next();
                    System.out.println(entry.getKey()+" , "+entry.getValue());
                    itr.remove();
                    Thread.sleep(2000);
                }
            }
        };

        t1.start();
        t2.start();
    }
}

Hashtable is synchronized, preventing two threads from accessing it at the same time.

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable . If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable .

HashMap is not synchronized.

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

Synchronizing does not prevent ConcurrentModificationException , because they both say :

The iterators returned by all of this class's "collection view methods" are fail-fast : if the [Hashtable/map] is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException .

Note that a single thread can cause ConcurrentModificationException by updating the Hashtable/HashMap directly while also iterating it. It doesn't require multi-threading to violate this rule.

ConcurrentHashMap says:

Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException . However, iterators are designed to be used by only one thread at a time.

So, HashMap is useful for single-threaded access.
Hashtable is useful for multi-threaded access, as long as they don't need to iterate the map.
ConcurrentHashMap allows updates and iteration by multiple threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM