Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 996
ngesh Avatar asked Mar 15 '26 14:03

ngesh


1 Answers

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

like image 103
Eric Rosenberg Avatar answered Mar 17 '26 05:03

Eric Rosenberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!