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

NX: notify instead of notifyAll?

 
Henrik Lund
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IMO threads may illegally consume CPU when notifyAll and wait is performed on a shared collection.
Instead of invoking wait on a shared collection, I think it's better to invoke wait on each single record (its record number):

This creates one "queue" per locked record instead of only one global "queue".
The unlock method would look something like:

Unlock wakes up at most one thread for the "queue" associated with a certain record number.
I think this solution solves the "consumes no CPU" requirement. Maybe I've foreseen something?
/Henrik Lund
[ February 03, 2004: Message edited by: Henrik Lund ]
 
Philippe Maquet
Bartender
Posts: 1872
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henrik,
Welcome to this forum!
I've implemented a similar solution though a little more complex: for each record number for which there is at least one thread waiting for a lock, I have a "real" queue of lock objects implemented through a LinkedList. That solution lets me grant locks in FIFO order. But as you, I don't use notifyAll(). And I agree with you that it better fulfills the "consume no CPU cycle while waiting" requirement.
Regards,
Phil.
 
Mark Smyth
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Instead of invoking wait on a shared collection, I think it's better to invoke wait on each single record (its record number):
code:
--------------------------------------------------------------------------------
lock(long recNo){ .... Long recordNumber = new Long(p_recNo); ... synchronized (m_lockMap) { ... while (lock.containsKey(recordNumber)) { ... recordNumber.wait(); ... } ... }}
--------------------------------------------------------------------------------

I am not an expert but as far as I know that wait and notify can only be invoked when you hold the monitor on an object, as you are synchronizing on the map and not on the Integer it contains, does this not throw an IllegalMonitorStateException?
 
Henrik Lund
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Sorry, my mistake! I did realise that I must have the lock on the object to call wait/notify (remembered it from SCJP when the IllegalMonitorStateException was thrown . I then tried to nest the locks (HashMap, record number), but finally changed my mind and implemented a LockManager like the one described in this thread.
Again, sorry for the mistake.
/Henrik
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic