Concurrency and HashMap
June 29, 2008
Post has been moved to our New Blog. http://blog.webscale.co.in/?p=25
Entry Filed under: Concurrency. .
5 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
1.
James | June 30, 2008 at 6:20 am
Nice, well explained article. I think this could do really well on JavaLobby. If you’re interested in reposting there, send me a mail and we can organise it
James
2.
dj | July 1, 2008 at 4:34 am
Nicely written. But I was not able to reproduce it. any clues ?
3.
Michael B | July 1, 2008 at 9:49 pm
“Finally i will leave you with this interesting bug in Java which says HashMap can…”
Wrong choice of words as it’s not a bug. A pitfall for the uninitiated? sure.
not thread-safe means not thread-safe. It’s a visibility issue that is goign to stay in there as it’s outside the scope of what a hashmap is suppose to do, use a ConcurrentMap implementation.
For an other perfect example where ppl also used there ’smart creativity’ check out:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
dj wrote:
“Nicely written. But I was not able to reproduce it. any clues ?”
Try reading this blog: http://java.dzone.com/articles/but-it-works-on-my-machine
In short the jvm you used might provide more visibility that it has too. The bottom line that which isn’t guaranteed to work is going to bit you in the ass -> small adaptation of murphies law.
4.
Rahul | April 7, 2009 at 8:37 am
I dont think the rule of thumb “use Thread safe collections
wherever concurrency is involved” is much of a use.
Consider you want to use HashTable instead of HashMap, when concurrency is required. As far as i know, only the individual methods in HashTable are synchronized, there is nothing that prevents Thread T2 from changing that HashTable, when thread T1 has come out of one method, say put() and is still to enter into get().
So, where concurrency is important, it is important to write code that takes care of it, instead of using Thread safe collections(which are obviously better than non thread safe collections, like HashMap in this case)
5.
Laurence Vanhelsuwe | July 13, 2009 at 8:58 am
Flagging down mutlithreaded accesses of NON threadsafe containers was one of the original features of our profiler. And, sure enough, most programs we’ve profiled seem to play Russian roulette with multithreaded accesses to HashMaps.