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,841
  • 7
  • 42
  • 51

2 Answers2

2

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
  • 43,537
  • 11
  • 94
  • 122
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,716
  • 3
  • 32
  • 59