Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is this a correct use of ConcurrentHashMap?

 
marwen Bakkar
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

This example is from http://www.javamex.com/tutorials/synchronization_concurrency_8_hashmap2.shtml
It's meant to demonstrate when to use ConcurrentHashMap in order to benefit from its atomic methods.
Following is the code with a traditional synchonized Map then one using ConcurrentHashMap.





I am almost sure the example is broken. When the query isn't present in the map, replace won't replace anything and the map will forever remain empty. Or am I missing something?

Edit: Actually replace(key, oldVal, newVal) throws NullPointerException when oldVal (or newVall) is null.
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your observations are right on the spot. This example is horrible. The correct way (in my opinion) would be to use AtomicInteger as a value, then use ConcurrentMap.putIfAbsent() to make sure each key is inserted only once and AtomicInteger.incrementAndGet() to increment the counter atomically.

I'd suggest to use Sun/Oracle's tutorials preferentially. Concurrency is covered here, though admittedly it does not go very deep. The quality of other tutorials is hard to evaluate, especially as tutorials are mostly read by beginners. Oracle's tutorial coupled with thorough reading of JDK classes' javadoc are probably better than relying on questionable third-party sources. The web is full of similar "pearls of wisdom", unfortunatelly.
 
marwen Bakkar
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi thanks for your reply. I agree with your approach. As far as concurrency resources go, I have just read "Java Concurrency in Practice" and it's the best book I've read. I think anything Josh Bloch is involved in is top quality.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic