Justin
Justin

Reputation: 11

Will changing an object from a hashmap affect the wait() method in multiple threads?

I have a hashmap of objects. Access to the hashmap is synchronized. Each object has a condition on whether or not it can be altered. If the object is not available via condition, object.wait(); is called and the current thread waits. If it is available, the object is altered and then put back into the hashmap:

HashMap<String, Boolean> availabilityMap = new HashMap<String, Boolean>();
HashMap<String, Object> objectMap = new  HashMap<String, Object>();
...
...

lock() {
     while (!availabilityMap.get(objectName)) {
          object = objectMap.get(objectName);
          object.wait();
     } 
     availabilityMap.put(objectName, false);
     object = objectMap.get(objectName);
}

object.attribute = newValue;

lock() {
     objectMap.put(objectName, object);
     availabilityMap.put(objectName, true);
     object = objectMap.get(objectName);
     object.notify();
}

Say thread1 is changing the attribute of this object, and thread2 is waiting to access the object. Thread1 finishes altering it, puts it back into the hashmap, and calls object.notify(). Will that object in thread2 still get the notification?

Upvotes: 0

Views: 496

Answers (1)

user207421
user207421

Reputation: 311001

Your question is rather obscure. The only things that will affect a wait() method are:

  1. notify() or notifyAll() called on the same object.
  2. Thread.interrupt().

If you notify() and only one thread is in wait(), that thread will get the notification. If multiple threads are in wait(), only one of them will get it. That's what notifyAll() is for.

Say thread1 is changing the attribute of this object, and thread2 is waiting to access the object. Thread1 finishes altering it, puts it back into the hashmap, and calls object.notify(). Will that object in thread2 still get the notification?

Of course. Why not? Getting it out of the hashmap and putting it back has nothing to do with it.

Upvotes: 1

Related Questions