0

I want to reproduce one scenario in which there are two threads accessing a shared HashMap. While one thread is copying the contents of the shared map into localMap using putAll() operation, second thread changes the shared map and CocurrentModificationException should be thrown.

I have tried but not able to reproduce the exception at the time when putAll operation is running. Each time either putAll gets complete before other thread does modification or putAll is called after other thread modification.

Can anyone please suggest how can I generate the scenario in java?

Thanks.

Infotechie
  • 1,653
  • 6
  • 23
  • 35

3 Answers3

0

Spin up both threads, have them running continuously.

Have one thread constantly doing putAll, the other constantly doing the modification.

Tim B
  • 40,716
  • 16
  • 83
  • 128
0
import java.util.HashMap;
import java.util.Map;

public class Example {
    private final HashMap<String, String> map = new HashMap<String, String>();

    public static void main(String[] args) {
        new Example();
    }

    public Example() {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                int counter = 0;
                while (true) {
                    Map<String, String> tmp = new HashMap<String, String>();
                    tmp.put("example" + counter, "example");
                    counter++;
                    map.putAll(tmp);
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    map.values().remove("example");
                }
            }
         });

        thread1.start();
        thread2.start();
    }
}

Unfortunately I cannot copy/paste the running code directly from my current workstation so I retyped it here so there might be a typing error.

As you can see the first thread is continuously adding values while the second thread iterates over the values in the Map. When it starts iterating over the values it expects a number of values (this value is initialized at the construction of the iterator). However because thread1 is continuously adding items this value is not as expected when the Iterator checks the actual amount of values that are in the map when it actual executes the remove code. This causes the ConcurrentModificationException.

Joel Witteveen
  • 387
  • 1
  • 9
0

If you just need a CocurrentModificationException to be thrown, you could implement your own Map implementation (HackedMap) to remove items from the HashMap when the HashMap tries to copy values from your HackedMap

Dave
  • 95
  • 8