0

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();
    }
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
pujan jain
  • 169
  • 2
  • The whole reason `Hashtable` was essentially deprecated was that it made you _think_ you had thread-safety when you didn't really. – Louis Wasserman May 12 '16 at 05:21
  • Possible duplicate of [How to debug ConcurrentModificationException?](http://stackoverflow.com/questions/840165/how-to-debug-concurrentmodificationexception) – Raedwald May 12 '16 at 07:21
  • @LouisWasserman Be careful when you say `Hashtable` and "deprecated" in the same sentence when I'm within earshot. :-) – Stuart Marks May 13 '16 at 06:27

1 Answers1

1

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247