0

The below code is receiving concurrent modificationexception when 2 thread access the same.

I would like to know whether

  1. Whether this exception can be avoided if we use concurrent Hashmap.
  2. If we use concurrent hashmap will there be any issue in a multithreaded environment.

or is there any other way to prevent this exception?

I donot intend use synchronzed as this code is used during polling. as one thread may have to wait for another to finish exceution.

The code is

HashMap<Integer, myModel> aServiceHash = new HashMap<Integer, myModel>();
HashMap<Integer, myModel> rServiceHash = new HashMap<Integer, myModel>();

for (myModel ser : serAccepted){
    aServiceHash.put(service.getOriginalDate(), ser);
}
for (myModel ser : serRequested) {
    if (aServiceHash.containsKey(service.getDate())) {
        aServiceHash.put(serv.getDate(), serv);
    }
    else 
        rServiceHash.put(service.getDate(), ser);
}

Referred http://examples.javacodegeeks.com/java-basics/exceptions/java-util-concurrentmodificationexception-how-to-handle-concurrent-modification-exception/

http://www.journaldev.com/378/how-to-avoid-concurrentmodificationexception-when-using-an-iterator

How to avoid HashMap "ConcurrentModificationException" while manipulating `values()` and `put()` in concurrent threads?

Using JSF 2.1,JDK 7.1.

Community
  • 1
  • 1
mehere
  • 1,487
  • 5
  • 28
  • 50

2 Answers2

1

HashMap is not thread safe. ConcurrentHashMapis thread safe. When accessing a map from different threads, prefer it to be concurrent for thread safety.

And yes, it will avoid the exception.There will be no multithreading issues from that direction. You'll still need to make sure no thread removes something you intend to use later.

Another way to prevent the exception is to lock the map before each insert, whether through synchronized block or a Lock object.

Stav Saad
  • 589
  • 1
  • 4
  • 13
  • if a thread wants to remove something, should i use iterator? – mehere Dec 01 '14 at 04:17
  • `ConcurrentHashMap` should be fine even if a thread just uses `remove()`. Of course you'll need to us iterator if this us while you are looping on the elements of the map – Stav Saad Dec 01 '14 at 05:03
1

Depending on your usage patterns and performance requirements, you could also build a copy-on-write map using a volatile HashMap delegate. This will give you one volatile read for each access whereas in ConcurrentHashMap you have a lot more, and they are a bit more expensive than ordinary reads or writes. Of course, copy-on-write schemes have their own drawbacks when you write to the map. But if you create the map from a pre-populated initial map and treat it as read-only afterwards, copy-on-write will be more efficient.

Ralf H
  • 1,392
  • 1
  • 9
  • 17