我正在尝试为下面的类实现Singleton
模式。我在任何时候在 JVM 中都应该只有 SingletonClass
类的单个实例。
下面的代码满足单例模式吗?请提出您的建议。
public class SingletonClass {
private static SingletonClass cache = null;
private static final Object LOCK = new Object();
// creates one single instance of the class
public static SingletonClass getInstance() {
if (cache == null) {
synchronized (LOCK) {
if (cache == null) {
cache = new SingletonClass();
}
}
}
return cache;
}
public static void main(String[] args) {
SingletonClass.getInstance();
}
}
最佳答案
有一篇关于实现单例模式的不同方法的好文章,包括您的方法: Reg's Tech article about Singleton
正如文章中提到的,您应该(如果您希望模式 100% 线程安全)还将 SingletonClass 字段声明为 volatile 的。另外,您不需要对象作为锁。只需使用synchronized(SingletonClass.class)
关于java - 带对象锁的单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986218/