Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronize and lock/unlock

 
Lina Mahl
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay...
I have read about lock/unlock and most I understand. But now my brother-in-law is making me confused!
if I have a method �lock� and in that method I place a value in a (static) HashMap
And if that method is synchronized, just one thread at a time can come in and place a value in the HashMap.
So if one thread comes along and place the value �5� in the HashMap all other threads must wait until that thread is finished even if they don�t want to lock the record �5�
Is that the case? and if so is that good?
I am getting confused because I am suddenly wandering over why I am using wait() and notifyAll() ?
Am I making myself clear?
What should I say to my (c-programming) brother-in-law?
/Lina
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lina,

if I have a method �lock� and in that method I place a value in a (static) HashMap
And if that method is synchronized, just one thread at a time can come in and place a value in the HashMap.

If you only have one lock manager per Data object, then there is no need to make the HashMap static. If you have multiple lock manager objects accessing the static Map then you will need to synchronize on the Map itself instead of the lock and unlock methods. I would suggest that you take the former approach.

So if one thread comes along and place the value �5� in the HashMap all other threads must wait until that thread is finished even if they don�t want to lock the record �5�
Is that the case? and if so is that good?

When a thread calls lock, you see if the requested record is already in the Map with locks.containsValue(record). If the record is not in the Map then the calling thread is given the lock and proceeds without wait()ing; otherwise it waits for the lock to become available. Not a real problem unless everybody wants to lock the same record simultaneously.

I am getting confused because I am suddenly wandering over why I am using wait() and notifyAll() ?

Don't wonder any further. That's what you need to do to bring order to the chaos of multiple threads selfishly trying to acquire locks.

What should I say to my (c-programming) brother-in-law?

Tell him that Java is a real programmer's language. Seriously though, the object monitor paradigm is vastly different from anything avaiable in C or its superset C++. Controlling concurrent modification is much simpler than using critical sections, mutexes and semaphores.
You're on the right track here, just stay the course.
Hope this helps,
Michael Morris
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic