Reputation: 14399
First off, I am working in Java 8.
I have an asynchronous task that produces this object as a result:
class Result {
private AtomicBoolean isComplete = new AtomicBoolean(false)
private Queue<String> state = new ConcurrentLinkedQueue<>();
public Queue<String> getState() {
return state;
}
public void setComplete() {
isComplete.set(true);
notifyAll();
}
public void waitUntilComplete() {
if (isComplete.get()) {
return;
}
wait();
}
}
I would like to have the optionally to block until the the task is complete. I was thinking about just using the .wait()
and .notifyAll()
.
I can't use a future as I do access the current state during the tasks execution.
Is this bad practice given that:
.wait()
and .notifyAll()
are public methods on Object.class
.Upvotes: 0
Views: 379
Reputation: 39477
As far as I'm aware, it is not bad practice to use the wait
, notify
, notifyAll
methods if you use them properly. It seems you don't use them properly though. Apparently it's either not clear to you what you want to achieve or how to achieve it (by using these methods).
I think you need something along these lines (code below).
Also, it seems, instead of LOCK
you can use this
too (in your case).
Consequently, you can make the whole two methods synchronized
(which implicitly means synchronized
on the monitor of this
).
class Result {
private boolean isComplete = false;
private static final Object LOCK = new Object();
public void setComplete() {
synchronized(LOCK){
isComplete = true;
LOCK.notifyAll();
}
}
public void waitUntilComplete() {
synchronized(LOCK){
while (!isComplete) {
LOCK.wait();
}
// do what you need to do when
// complete is already equal to true
}
}
}
Upvotes: 1