Java – the caller blocks until getfoo () has a value ready?
I have a java thread that exposes properties that other threads want to access:
class MyThread extends Thread { private Foo foo; ... Foo getFoo() { return foo; } ... public void run() { ... foo = makeTheFoo(); ... } }
The problem is that it takes some time from running time to available time The caller can call getFoo () before that and get a null.. Once initialization occurs, I'd rather they just block, wait and get the value Foo has never changed Until it's ready, it will be in milliseconds, so I'm happy to use this method
Now, I can do this through wait() and notifyall(), and I will do it 95% of the time But I wonder what you'll do? Is there an original Java util. Concurrent will do this, I missed it?
Or, how would you build it? Yes, it volatilizes foo Yes, synchronize on the internal lock object and put the check in the while loop until it is not empty Did I miss anything?
Solution
If foo is initialized only once, countdown latch is very suitable
class MyThread extends Thread { private final CountDownLatch latch = new CountDownLatch(1); ... Foo getFoo() throws InterruptedException { latch.await(); /* Or use overload with timeout parameter. */ return foo; } @Override public void run() { foo = makeTheFoo() latch.countDown(); } }
The latch provides the same visibility behavior as the volatile keyword, which means that the reading thread will see the value of the thread allocated foo, even if foo is not declared volatile