简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM