When doing lazy initialization of a static singleton in Java you can do this:
public class Bob {
private static class SingletonWrapper {
private static final Bob instance = new Bob();
}
public static Bob getInstance() {
return SingletonWrapper.instance;
}
}
Because the inner class SingletonWrapper
is only loaded when first accessed the Bob()
is not created until getInstance()
is called.
My question is whether there are any similar tricks that can be used to do a lazy instantiation of a member variable in a non-static context.
public class Bob {
// Clearly this doesn't work as not lazy
private final InnerWrapper wrapper = new InnerWrapper();
private class InnerWrapper {
private final Jane jane = new Jane();
}
public Jane getJane() {
return wrapper.jane;
}
}
Is there any way we can have an instance of Jane
within Bob
and thread safely have the instance only created on demand without using double check locking or AtomicReference
. Ideally the get method should remain as simple as the one in these examples but if that is not possible then the simplest and fastest possible (most efficient) execution of the get
method would be ideal.