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.
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.
您需要将final
添加到static
变量ourInstance
以防止以后进行任何修改,然后您将拥有一个完美的线程安全singleton
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.