aspose file tools*
The moose likes Threads and Synchronization and the fly likes Is this a correct use of ConcurrentHashMap? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Is this a correct use of ConcurrentHashMap?" Watch "Is this a correct use of ConcurrentHashMap?" New topic
Author

Is this a correct use of ConcurrentHashMap?

marwen Bakkar
Ranch Hand

Joined: Jan 28, 2010
Posts: 84
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

Joined: Aug 22, 2010
Posts: 3611
    
  60

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

Joined: Jan 28, 2010
Posts: 84
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is this a correct use of ConcurrentHashMap?