0

IntelliJ can autogenerate a template for a singleton class, which looks something like this:

public class A {
    private static A ourInstance = new A();

    public static A getInstance() {
        return ourInstance;
    }

    private A() {
    }
}

Is this implementation of singleton thread-safe? I have read about implementing thread-safe singletons through enums. I was wondering if the above implementation is thread-safe as well. As 'ourInstance' has been defined as static and initialized as a class variable, there should be just one copy of the object.

krackoder
  • 2,573
  • 6
  • 40
  • 45

2 Answers2

1

Yes, this implementation is thread-safe. Static fields are guaranteed to be initialised and visible before this class or any instance of it are available to the rest of java code.

Nikem
  • 5,313
  • 2
  • 30
  • 55
1

You need to add final to your static variable ourInstance to prevent any later modifications then you will have a perfect thread safe singleton.

Nicolas Filotto
  • 41,524
  • 11
  • 90
  • 115