java - ConcurrentModifcationException when adding value to hashmap -
the below code receiving concurrent modificationexception when 2 thread access same.
i know whether
- whether exception can avoided if use concurrent hashmap.
- if use concurrent hashmap there issue in multithreaded environment.
or there other way prevent exception?
i donot intend use synchronzed code used during polling. 1 thread may have wait finish exceution.
the code is
hashmap<integer, mymodel> aservicehash = new hashmap<integer, mymodel>(); hashmap<integer, mymodel> rservicehash = new hashmap<integer, mymodel>(); (mymodel ser : seraccepted){ aservicehash.put(service.getoriginaldate(), ser); } (mymodel ser : serrequested) { if (aservicehash.containskey(service.getdate())) { aservicehash.put(serv.getdate(), serv); } else rservicehash.put(service.getdate(), ser); }
http://www.journaldev.com/378/how-to-avoid-concurrentmodificationexception-when-using-an-iterator
using jsf 2.1,jdk 7.1.
hashmap
not thread safe. concurrenthashmap
is thread safe. when accessing map different threads, prefer concurrent thread safety.
and yes, avoid exception.there no multithreading issues direction. you'll still need make sure no thread removes intend use later.
another way prevent exception lock map before each insert, whether through synchronized block or lock
object.
Comments
Post a Comment