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
- you iterator collection
- the collection structurally modified, making iterator no longer valid
- 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
- it modified in thread, cannot see in code, or
- the
mapimplementation that, get() treated structural modified. access-ordered linkedhashmap example. (we cannot see in code either)
there different solutions, depending on need:
- using
concurrenthashmap, guarantees iterator not throwingconcurrentmodificationexception. iteration base on order @ time iterator created - if thread updating map cause problem, may consider proper synchronization control on map when iterating through it
- if caused access-ordered
linkedhashmap, may change bit in logic, iterating throughyourmap.entries(), don't need useget()value.
Comments
Post a Comment