Java Reference
In-Depth Information
The map referred to by unsyncMap is a full, but unsynchronized, im-
plementation of the Map interface. The Map returned by synchronizedMap
has all relevant methods synchronized, passing all calls through to the
wrapped map (that is, to unsyncMap ). Modifications made through either
map are visible to the otherthere is really only one map with two dif-
ferent views: the unwrapped, unsynchronized view referenced by unsyn-
cMap , and the wrapping, synchronized view referenced by syncMap :
Because the underlying collection is unsynchronized, you must be very
careful what you do with unsyncMap . The safest alternative is to drop the
reference and do all work through syncMap . If you do not, you must be
sure that you carefully control concurrency. The wrapper synchronizes
on itself, so you could use syncMap to synchronize access on the collec-
tion and then use unsyncMap safely inside such code:
// add a lot of elements but grab the lock only once
synchronized (syncMap) {
for (int i = 0; i < keys.length; i++)
unsyncMap.put(keys[i], values[i]);
}
Iterators returned by synchronized wrappers are not synchronized but
must be manually synchronized in a similar manner when needed:
synchronized (syncMap) {
System.out.println("--- map contents:");
Search WWH ::




Custom Search