Not perfect, but perhaps it could work in your case: create a class that extends HashMap, but that internally has a synchronized Map. Then, delegate all method calls to your internal map. On the constructors, create a new HashMap, then synchronize it. Something like this:
public class SynchronizedHashMap<K, V> extends HashMap<K, V> {
private Map<K, V> internalMap;
public SynchronizedHashMap(int initialCapacity, float loadFactor) {
internalMap = Collections.synchronizedMap(new HashMap<>(initialCapacity, loadFactor));
}
public SynchronizedHashMap(int initialCapacity) {
internalMap = Collections.synchronizedMap(new HashMap<>(initialCapacity));
}
public SynchronizedHashMap() {
internalMap = Collections.synchronizedMap(new HashMap<>());
}
public SynchronizedHashMap(Map<? extends K, ? extends V> m) {
internalMap = Collections.synchronizedMap(new HashMap<>(m));
}
@Override public int size() {
return internalMap.size();
}
@Override public boolean isEmpty() {
return internalMap.isEmpty();
}
@Override public boolean containsKey(Object o) {
return internalMap.containsKey(o);
}
...
}
And remember, that's why you should be coding for interfaces, not to concrete implementations. Your interface should return a Map, and your client should consume a Map, without knowledge about which Map it is.
new HashMap<>(map), or do they want the original? - Paul BoddingtonHashMap<...> map = new HashMap<>();Create and distributeCollections.synchronizedMap(map);as you wish, then, when you need the unsynchronized version, just use the originalmap. - aioobeMap, notHashMap. Your situation is exactly the reason why theMapinterface exists. - Jiri Tousek