I’m working in an Android project with multithreading. Basically I have to wait to the server to respond before sending more data.
The data sending task is delimited by the flag boolean hasServerResponded
so the Thread
will loop infinitely without doing anything until the flag becomes true
.
Since this boolean
isn’t declared as volatile
(yet), and also looping without doing anything wastes resources, I thought maybe I should use AtomicBoolean
and also implement wait() / notify()
mechanism.
Should I use the AtomicBoolean
object notify()
and wait()
methods or should I create a lock Object
?
If you are not using the volatile yet and to get atomic features it is OK to use AtomicBoolean. And if you are using AtomicBoolean it is better to use its own methods and it may give you some sort of a performance advantage.
IMO, working with low level wait/notify is bug prone and usually a poor idea. Java has wonderful higher level concurrency constructs. In this example, use a Queue.
the typical way to implement this is:
void waitForResponce() throws InterruptedException{
synchronized(this){
while(!responded)wait();
}
}
private boolean responded=false;
void signalResponce(){
synchronized(this){
responded=true;
}
}
the while loop is to guard against spurious wakeups and the synchronized surrounds the while to guard against race conditions
if you which to allow resets of the signal it gets tougher
however in android there is an event loop and async tasks that you can leverage which has callback to the ui thread build in