• Post Reply Bookmark Topic Watch Topic
  • New Topic

cloning synchronized hashmaps

 
Annekee Dufour
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Annekee Dufour
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, this really helps. Obviously, simple and neat is not always wrong!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!