*
The moose likes Threads and Synchronization and the fly likes HashMap Lock Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "HashMap Lock" Watch "HashMap Lock" New topic
Author

HashMap Lock

Shankar sanjay
Ranch Hand

Joined: Sep 14, 2009
Posts: 117
Hi I have static hashMap.

When Thread1 tries to update key "key1" and Thread2 tries to retrive value for "Key1" at the same time.

I have already maintain write lock while update the hashMap. Do I need to keep readLock.
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

Why not make the HashMap synchronized by using..

Collections.synchronizedMap(Map m);

This wil solve both the problems..Write as well as read..


SCJP6.0,My blog Ranchers from Delhi
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Yes, you want Thread-2 to be aware that Thread-1 is busy with the key-1
object (by locking the Class object in this case), so that Thread-2 waits for
things to settle down before it is allowed to read key-1.

Jim ... ...


BEE MBA PMP SCJP-6
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

I think the answer depends on what it actually means to "update" the key of an entry. There are three possible meanings for that:

(1) Change the internal state of the object which is the key.

(2) Change the internal state of the object which is the value.

(3) Assign a new object to be the value.

It does help to have precise descriptions when you are discussing concurrency.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 409
    
    1

Why not use ConcurrentHashMap its very efficient at sorting out the minimum amount of over head ? Any time it can get away without locking it will and be more efficient than just synchronizing your hash map.

If you want to do it the hard and inefficient/slow way your almost certainly going to need the readLock for visibility if nothing else. As to what your actually updating, whatever it is needs happens before ordering usually thought of as a read memory barrier regardless of the actual locking i.e. you need a write barrier after the update and a read before the read (ok strictly you need happens before ordering as you can have that without a memory barrier literally) ... if all this is confusing I refer you to my first simple suggestion just use ConcurrentHashMap .


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Yes Chris, I do find your explanation a bit confusing.
Can you elaborate (and/or) simplify a bit. Thanks.

Jim ... ...
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 409
    
    1

The really simple answer to the question was use ConcurrentHashMap, the second best answer was just leave that readLock there (I haven't seen the code obviously so I'm guessing at what it looks like)

Assuming we're going to ignore the simple solution ..

Which bit ;-) . Could you elaborate on which bit you find confusing
e.g.
the benefits of ConcurrentHashMap vs synchronized map
happens before ordering
memory barriers / fences
Java Memory Model

ConcurrentHashMap is well written up in blogs and books , it can (does its best to) allow concurrent writes and reads and assures correct publication of the data it references. I can recommend some if it helps. Also we never mentioned this but was read / write locks a good performance choice at all according to the books on my desk the answer is not always ;-)

As regards the rest , its difficult to know you level are you an expert or a novice (I suspect both read these forums) ;-) I usually start with do you understand what the volatile keyword does in the new Java Memory model (I'm not recommending volatile use its just a good level indicator) . I guess I assumed mini wasn't an expert so a simple solution was best.

Essentially if one thread writes and another reads the same memory you MUST establish establish "happens before ordering "or you run the risk your reading thread will miss your writes (they never happen in the second threads view of the world an effect like same variable two different values) possibly indefinitely ... your write and read locks are handling this for you but if you remove one of them it all gets very complicated (this is a separate issue to the actual locking) . The simplified and strictly incorrect explanation is that the without the readLock you have no guarantee that the second thread ever sees the results of the first threads writes (or you need to add something else to achieve the guarantee).

At its simplest if a class contains say a boolean with a getter and setter and one thread reads and one writes if you synchronize the set you should synchronize the get.


Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Chris: I am a relative newbee and currently working on my Java developer certification.
It seems that the original question is about proper use of the key word 'synchronized' for
a HashMap but your answer doesn't explore this. A discussion about "happens before"
skips over this simple solution provided by the language. Do you not like this tool?

Jim ... ...
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 409
    
    1

The original question which is a good one and is a very common gotcha is why do I need a ReadLock and the answer is just complicated, the best thing is to just obey the simple rule and not ask ;-0 but as the question was asked directly I gave an answer. The thread was then diverted ..

I like synchronized its a wonderful keyword I use it a lot but note read and write locks were added to allow improvements to Java so to dismiss them out of hand is a mistake and they can if used correctly deliver better performance i.e. his solution could beat the synchronized one (notice I'm careful with my could)

I actually used synchronization a lot on my SCJD and did very, very nicely ;-) but most people and books will use Read and Write locks on the developer certification and I went into the essay questions fully armed with what their advantages are and how and when they affect performance e.g. % reads vs % writes etc etc . If your going to do the developer certification I would suggest a full understanding of their potential advantages should be a goal.

The thread was then diverted to what is a simpler solution and it was suggested we might use ...



I'm suggesting a simpler and quicker solution is to use ConcurrentHashMap surely its simpler to just new one than new a map and then add a synchronized wrapper. I see as the better simpler solution.
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Chris: Are you referring to the java.util.concurrent package?
Are there other packages that also apply here?

Jim... ...
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 409
    
    1

java.util.concurrent package is where ConcurrentHashMap lives ;-) and most "new" concurrency features.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Thanks for the tips . . .
 
jQuery in Action, 2nd edition
 
subject: HashMap Lock
 
Similar Threads
Hibernate mapping HashMap to row
Some Locking Advice
Locking question
How do i make my class immutable?
Synchronizing read and find