java - ConcurrentModifcationException when adding value to hashmap -


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

i know whether

  1. whether exception can avoided if use concurrent hashmap.
  2. 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); } 

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 avoid hashmap "concurrentmodificationexception" while manipulating `values()` , `put()` in concurrent threads?

using jsf 2.1,jdk 7.1.

hashmap not thread safe. concurrenthashmapis 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

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -