JavaFAQ Home » General Java
Question: I know that Hashmap implementation is not synchronized. How
can I synchronize it?
Answer: Really good answer often can be found in API!
"If multiple threads access this map concurrently, and at least one of the
threads modifies the map structurally, it must be synchronized externally. (A
structural modification is any operation that adds or deletes one or more
mappings; merely changing the value associated with a key that an instance
already contains is not a structural modification.) This is typically
accomplished by synchronizing on some object that naturally encapsulates the
map. If no such object exists, the map should be "wrapped" using the
Collections.synchronizedMap method. This is best done at creation time, to
prevent accidental unsynchronized access to the map:
Map m =
The iterators returned by
all of this class's "collection view methods" are fail-fast: if the map is
structurally modified at any time after the iterator is created, in any way
except through the iterator's own remove or add methods, the iterator will throw
a ConcurrentModificationException. Thus, in the face of concurrent modification,
the iterator fails quickly and cleanly, rather than risking arbitrary,
non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast
behavior of an iterator cannot be guaranteed as it is, generally speaking,
impossible to make any hard guarantees in the presence of unsynchronized
concurrent modification. Fail-fast iterators throw
ConcurrentModificationException on a best-effort basis. Therefore, it would be
wrong to write a program that depended on this exception for its correctness:
the fail-fast behavior of iterators should be used only to detect bugs."
From Java API (v 1.4.1)
Our older tips: March 22, 2001 - October 21, 2002
All published and not published on the site tips read
Printer Friendly Page
Send to a Friend
Search here again if you need more info!