Lazy initialization for free
Asked Answered
E

1

6

In an article on the double-checked locking idiom, I found this quote:

One special case of lazy initialization that does work as expected without synchronization is the static singleton. When the initialized object is a static field of a class with no other methods or fields, the JVM effectively performs lazy initialization automatically.

Why is the emphasized part important? Why doesn't it work if there are other methods or fields?

(The article is already more than 10 years old. Is the information still relevant?)

Ermeena answered 2/2, 2013 at 0:26 Comment(1)
+1 interesting question. Initially my guess would have been that that is the only time the JVM can be sure there won't be a call on that object before it is referenced from outside the class; but that doesn't seem to illuminate anything.Wey
C
5

What it means is probably that, if a class has no other methods or fields, then you only access it for the singleton, so the singleton is only created when demanded. Otherwise, for example

class Foo 
{
    public static final Foo foo = new Foo();

    public static int x() { return 0; }
}

class AnotherClass
{
    void test() 
    {
        print(Foo.x());
    }
}

here, foo was instantiated, though it was never asked for.

But it's ok to have private static methods/fields, so others won't trigger class initialization by accident.

Coating answered 2/2, 2013 at 0:43 Comment(3)
"a static field of a class with no other methods or fields" - but in your example Foo has a method x()Vi
Yes, because he was giving the counter-example to the case in the article, where the singleton isn't really lazy because it might be created before it is needed.Pickpocket
Ah okay, but in Singleton implementations, you typically only have one static method which returns the instance, and all other methods are non-static, right?Ermeena

© 2022 - 2024 — McMap. All rights reserved.