ngesh
ngesh

Reputation: 13501

How do I avoid this busy-wait?

public int getChildrenCount(int groupPosition) {
    if(children == null){
        new SalesRequest().execute(); // runs in other thread which 
                                      // initialises children with some value.
        while(children == null){
            // I'm doin this to avoid null pointer Exception.
            // So it comes out of the loop only when childern 
            // gets initialised.
        }
    }
    return children.length;
}

But I'm not satisfied with the way I'm handling this. Is there a better way to do this?

Upvotes: 3

Views: 3064

Answers (2)

GETah
GETah

Reputation: 21409

There are a multiple of possible solutions for this issue. The most elegant way is as Eric mentioned above, CountDownLatch. Here is how you could proceed:

// Lock to signal Children are created
CountDownLatch childrenReady = new CountDownLatch(1/*wait for one signal*/);
public int getChildrenCount(int groupPosition) {
    if(children == null){
        SalesRequest request = new SalesRequest(childrenReady /*pass on this lock to worker thread*/);
        request().execute(); // runs in other thread which 
                                      // initialises children with some value.
        childrenReady.await();        // Wait until salesRequest finishes
        while(children == null){
            // I'm doin this to avoid null pointer Exception.
            // So it comes out of the loop only when childern 
            // gets initialised.
        }
    }
    return children.length;
}

In SalesRequest.execute method, you could have the following:

// Populate and create children structure of the calling object
// When done, signal to callee that we have finished creating children 
childrenReady.countDown(); // This will release the calling thread into the while loop

Also, make sure you are not calling getChildrenCount() from the UI thread otherwise your application will hang and will loose its responsiveness until you get an answer from the server.

Upvotes: 3

Eric Rosenberg
Eric Rosenberg

Reputation: 1533

You could use a CountDownLatch to wait for the other thread to complete.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CountDownLatch.html

Upvotes: 5

Related Questions