Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

migrated from codereview.stackexchange.com Jun 7 at 13:36

This question came from our site for peer programmer code reviews.

3 Answers 3

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.

share|improve this answer

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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.