0

I've seen this answer here showing how to do thread safe lazy initialization of a static final singleton.

But what is the best solution if the class you are lazy loading isn't final? (It has some methods you want to call after creating it)

Is it safe to just put the method calls in a static block?

public class Something {

    private static class LazyHolder {
            public static final Something INSTANCE = new Something();
            static {
                    INSTANCE.setValue("foo");
            }
    }

    public static Something getInstance() {
            return LazyHolder.INSTANCE;
    }
}
LockieR
  • 370
  • 6
  • 19

1 Answers1

1

This is IODH (Initialize on demand method) idiom.

But what is the best solution if the class you are lazy loading isn't final? (It has some methods you want to call after creating it)

It does not really matter if your "INSTANCE" is final or not. It will be lazily loaded (when you call getInstance method for the first time).
The purpose of making INSTACE final is to ensure, It always point to one kind of object but you are free to modify the object properties.

Tarun
  • 3,162
  • 3
  • 29
  • 45