Friday, December 27, 2013

I have a Map which is to be modified by several threads concurrently.
There seem to be three different synchronized Map implementations in the Java API:
  • Hashtable
  • Collections.synchronizedMap(Map)
  • ConcurrentHashMap
From what I understand, Hashtable is an old implementation (extending the obsolete Dictionaryclass), which has been adapted later to fit the Map interface. While it is synchronized, it seems to have serious scalability issues and is discouraged for new projects.
But what about the other two? What are the differences between Maps returned byCollections.synchronizedMap(Map) and ConcurrentHashMaps? Which one fits which situation?
share|improve this question
3 
I would suggest to read this article as to how ConcurrentHashMap works and what guarantees it can give.codercorp.com/blog/java/… –  Smiles in a Jar Aug 16 '11 at 3:40
 
@SmilesinaJar : very userful article –  Krsna Chaitanya yesterday 
add comment

11 Answers

up vote102down voteaccepted
For your needs, use ConcurrentHashMap. It allows concurrent modification of the Map from several threads without the need to block them. Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).
Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.
share|improve this answer
2 
Looking at the source code, the synchronized map is only an implementation with one mutex (blocking) while the ConcurrentHashMap is more complex to deal with concurrent access –  Vinze Feb 4 '09 at 9:36
29 
Please also note that the ConcurrentHashMap does not allow null keys or values. So they are NOT equal alternatives of a synchronized map. –  onejigtwojig Oct 20 '11 at 19:42 
7 
add comment
The "scalability issues" for Hashtable are present in exactly the same way inCollections.synchronizedMap(Map) - they use very simple synchronization, which means that only one thread can access the map at the same time.
This is not much of an issue when you have simple inserts and lookups (unless you do it extremely intensively), but becomes a big problem when you need to iterate over the entire Map, which can take a long time for a large Map - while one thread does that, all others have to wait if they want to insert or lookup anything.
The ConcurrentHashMap uses very sophisticated techniques to reduce the need for synchronization and allow parallel read access by multiple threads without synchronization and, more importantly, provides an Iterator that requires no synchronization and even allows the Map to be modified during interation (though it makes no guarantees whether or not elements that were inserted during iteration will be returned).
share|improve this answer
1 
Now that's what I wanted! :) The no-synchronized Iterator is just pure sweetness alone! Thansk for the info! :) (: –  Kounavi Jun 30 '11 at 20:28 
 
Great answer..but does it mean during retrieval thread will not get the latest updates since reader threads are not in sync. –  MrA May 13 at 11:54
 
@MrA: Are you asking about the ConcurrentHashMap? And what do you mean by "retrieval"? – Michael Borgwardt May 13 at 12:24
1 
@Michael Borgwardt for ConcurrentHashmap for eg. suppose there are multiple threads. some of them are updating the Map and some of them are getting data from that same map. SO in this scenario when threads are trying to read is it guaranteed that they will get the latest data that has been updated since reader threads does not have to hold locks. –  MrA May 13 at 23:12
add comment
╔═══════════════╦═══════════════════╦═══════════════════╦═════════════════════╗
   Property         HashMap           Hashtable        ConcurrentHashMap  
╠═══════════════╬═══════════════════╬═══════════════════╬═════════════════════╣ 
      Null          allowed          not allowed          not allowed     
  values/keys                                                             
╠═══════════════╬═══════════════════╬═══════════════════╬═════════════════════╣
Is thread-safe        no                 yes                   yes        
╠═══════════════╬═══════════════════╬═══════════════════╬═════════════════════╣
     Lock             not           locks the whole   locks the portion of 
  mechanism        applicable            map                   map         
╠═══════════════╬═══════════════════╩═══════════════════╬═════════════════════╣
   Iterator                   fail-fast                      fail-safe      
╚═══════════════╩═══════════════════════════════════════╩═════════════════════╝
share|improve this answer
add comment
ConcurrentHashMap is preferred when you can use it - though it requires at least Java 5.
It is designed to scale well when used by multiple threads. Performance may be marginally poorer when only a single thread accesses the Map at a time, but significantly better when multiple threads access the map concurrently.
I found a blog entry that reproduces a table from the excellent book Java Concurrency In Practice, which I thoroughly recommend.
Collections.synchronizedMap makes sense really only if you need to wrap up a map with some other characteristics, perhaps some sort of ordered map, like a TreeMap.
share|improve this answer

4 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes