Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initialization for free

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?)

like image 514
fredoverflow Avatar asked Oct 06 '22 04:10

fredoverflow


1 Answers

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.

like image 124
irreputable Avatar answered Oct 10 '22 14:10

irreputable