Java- Why this program not throwing concurrent Modification exception
Asked Answered
S

2

4

I am trying to induce a concurrent modification exception by accessing a HashMap instance variable reference, but this program is not throwing the error. Appreciate if you could help me to understand.

package Threads;
import java.util.HashMap;

public class ProducerConsumer {

    private HashMap<String, String> sharedMap = new HashMap<String,String>();

    public void putMethod(){

        for (int count=0; count<100; count++)
        {
        System.out.println("Adding into sharedMap:"+count);
        sharedMap.put(Integer.toString(count),Integer.toString(count));
        }
    }

    public static void main(String [] args) throws InterruptedException{

    final ProducerConsumer pc1=new ProducerConsumer();
    Thread t1= new Thread( new Runnable(){

        @Override
        public void run() {
            pc1.putMethod();
        }

    });

    Thread t2= new Thread( new Runnable(){

        @Override
        public void run() {
            pc1.putMethod();
            }   
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    }
}
Steady answered 30/4, 2015 at 11:0 Comment(0)
O
2

The add() method does not detect concurrent modifications and therefore will not throw a ConcurrentModificationException (that's what anonymous already said).

However, concurrent access to a HashMap can be dangerous, though. Read more about this in another post.

You can enforce a ConcurrentModificationException if you read from the HashMap in parallel:

...
public void putMethod() { ... }
public void iterateMethod() {
    sharedMap.keySet().stream().forEach((s) -> {
        System.out.println("Read key " + s);
    }
}

public static void main(String[] args) throws InterruptedException {
    ...
    t1.start();
    Thread.sleep(20); // sleep time depends on your computer's speed ;-)
    t2.start();
    ...
}
...
Outcaste answered 30/4, 2015 at 12:22 Comment(1)
Thanks.. In the code that i originally posted the sharedMap object is accessed by thread 1 and 2 concurrently. My understanding was if any collection is accessed modified concurrently ( add, remove, replace..) then it should through the concurrent modification. Because technically the object is modified concurrently. However, it appears to be true only in case of iteration not addition.. Thanks again..Steady
J
1

The exception needs to be thrown by the implementing method that is being invoked on the class. From the Javadoc, it looks like the HashMap Iterators are fast-fail Iterators; meaning it will throw it if you are Iteratoring while adding. The add method will add the item to the map if the key doesn't exist or replace it if it does, I don't think that would throw the exception you're trying to produce.

Jewry answered 30/4, 2015 at 12:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.