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

Is a WeakHashMap valid for a threading point of view?

 
John Cogan
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm using the WeakHashMap approach to satisify the Locking criteria for URLyBird 1.3.1

I have my Data class in which I have the following:

private static WeakHashMap lockedRecords = new WeakHashMap();

Now, an instance of the Data class is created for every client. But because lockedRecords is static, it is the same accross all instances.


In the lock() method, I synchronize on lockedRecords:

synchronized (lockedRecords) {

...

I call wait on lockedRecords, this waits until another instance/client releases the lock on lockedRecords.


while (lockedRecords.containsValue(lrecNo)) {
try {


lockedRecords.wait();


My question is, does it make sense for the same object (lockedRecords) to be waiting for a notifyAll from itself albeit from a different instance? All instances share the same static object.
I understand how threadking wait/notify work when you are talking about different objects being involved in the wait and notify.
Best regards,
John
 
Frans Janssen
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is, does it make sense for the same object (lockedRecords) to be waiting for a notifyAll from itself albeit from a different instance? All instances share the same static object.

Hi John,

When a thread waits on an object, it always waits for a notify from the same object instance. Whether or not that object is referenced as a static member by another class does not make any difference.

So your code makes sense. It is not the most efficient though, because a notifyAll will wake up all waiting threads, not just those waiting for a particular record.

Frans.
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 12014
220
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi John & Frans,

Originally posted by Frans Janssen:
So your code makes sense. It is not the most efficient though, because a notifyAll will wake up all waiting threads, not just those waiting for a particular record.


I agree with both statements. The question you have to ask though, is does the extra efficiency warrant the extra code complexity? (Hint: check your instructions, does it say anything about clarity and maintainability? )

Regards, Andrew
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic