java - Concurrent Access HashMap -


the code below runs issue of java.util.concurrentmodificationexception. there way prevent or allow this?

public void savehomes() throws ioexception {     bufferedwriter br;     br  = new bufferedwriter(new filewriter(homefile));     map<string, location> homesloc;      system.out.println(homes2.keyset());     (string player : homes2.keyset()) {         homesloc = homes2.get(player);         (string name : homesloc.keyset()) {             br.write(player + " " + homesloc.get(name) + " " + name);             br.newline();             br.flush();         }     }      br.close(); } 

most of answers here seem have misunderstood meaning of concurrentmodificationexception, making them incomplete or incorrect answers.

first thing need understand is, concurrentmodificationexception has nothing concurrent access collection multiple threads. can happen in single-threaded application. so, using synchronized map implementations not correct solution problem.

concurrentmodificationexception happens when

  1. you iterator collection
  2. the collection structurally modified, making iterator no longer valid
  3. if use iterator now, throw concurrentmodificationexception.

therefore, map accessed single thread, may still have problem.

from code, there no obvious logic modified collections (homes2 / homesloc). may caused

  1. it modified in thread, cannot see in code, or
  2. the map implementation that, get() treated structural modified. access-ordered linkedhashmap example. (we cannot see in code either)

there different solutions, depending on need:

  1. using concurrenthashmap, guarantees iterator not throwing concurrentmodificationexception. iteration base on order @ time iterator created
  2. if thread updating map cause problem, may consider proper synchronization control on map when iterating through it
  3. if caused access-ordered linkedhashmap, may change bit in logic, iterating through yourmap.entries(), don't need use get() value.

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -