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?)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With