I just came across some code which uses wait-notify construct to communicate with thread defined in a class, by its other member-methods. Amusingly, after acquiring lock, all thread does in synchronized scope is timed-wait on same lock (see below snippet). Later, in non-synchronized scope, thread executes its key function (ie '//do something useful1').
My best guess at purpose of this mechanism is, to minimize thread's resource-consumption until call to 'someMethod' is made by other thread. What do experts think? If this is the case, what are better ways of achieving this behavior?
class SomeClass{
public void run() {
while (!isShuttingDown){
try {
synchronized (SomeClass.class) {
SomeClass.class.wait(500);
}
} catch (Throwable e) {
LOGGER.info(SomeClass.class.getSimpleName() + " reaper thread interrupted", e);
}
//do something useful1
}
}
public synchronized void someMethod(){
//do something useful2
synchronized (SomeClass.class) {
SomeClass.class.notifyAll();
}
//do something useful3
}
}