I would like to use a synchronized HashMap. I understand I can get one using Collections.synchronizedMap(myMap). However, the return value is a Map and not a HashMap. So now I can no longer clone. Should I build my own clone method? Or should I use the unsynchronized HashMap and do the synchronization in every method? Or is there another way around this?
Assuming you really need a separate copy of the map, you can simply use Map newMap = Collections.synchronizedMap(new HashMap(oldMap)); Note that you may want to put this inside code that is synced on oldMap, since the HashMap constructor will be accessing data from oldMap, and although the resulting new HashMap will eventually be wrapped in sync code by synchronizedMap(), there's no explicit sync during construction. So you need to determine if oldMap is already being accessed by more than one thread, and is also subject to structural modification by at least one of those threads. If so, you need additional sync during construction.
"I'm not back." - Bill Harding, Twister
Joined: Nov 04, 2003
Thanks a lot, this really helps. Obviously, simple and neat is not always wrong!