Callers block until getFoo() has a value ready?
Posted
by Sean Owen
on Stack Overflow
See other posts from Stack Overflow
or by Sean Owen
Published on 2010-05-14T19:47:23Z
Indexed on
2010/05/14
20:04 UTC
Read the original article
Hit count: 226
I have a Java Thread
which exposes a property which 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 short time from the time this runs until foo
is available. Callers may call getFoo()
before this and get a null
. I'd rather they simply block, wait, and get the value once initialization has occurred. (foo
is never changed afterwards.) It will be a matter of milliseconds until it's ready, so I'm comfortable with this approach.
Now, I can make this happen with wait()
and notifyAll()
and there's a 95% chance I'll do it right. But I'm wondering how you all would do it; is there a primitive in java.util.concurrent
that would do this, that I've missed?
Or, how would you structure it? Yes, make foo
volatile. Yes, synchronize on an internal lock Object
and put the check in a while
loop until it's not null
. Am I missing anything?
© Stack Overflow or respective owner