Sha*_*ire 1 java singleton multithreading design-patterns
我已经实现了Singleton类,如下所示:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private synchronized static void createInstance() {
instance = new Singletone();
}
public static Singleton getInstance() {
if(instance == null){
createInstance();
}
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
但我想知道它是否是单例的正确实现.多线程环境中是否有任何问题.
public enum Singleton {
INSTANCE;
private int val;
public int getVal() {
return val;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Singleton.INSTANCE.getVal();
Run Code Online (Sandbox Code Playgroud)
这是Java版本> 5.0的完美单例,您可以在其中获得枚举支持.
在Joshua Bloch的Effective Java中也提到过.关于它的博客文章:Enum Singleton
更新:
此外,只有当您100%确定需要单身时,请使用单身人士!它会破坏代码的可测试性!但你无法避免在工厂里说到的地方.
但请不要滥用它,在实际需要的地方使用它.了解它的用途.
您的实施几乎是正确的.问题是它不是线程安全的.可以getInstance()同时输入2个单独的线程,检查该实例是否为null,然后创建2个类的实例.这是修复:
public static synchronized Singletone getInstance() {
if(instance == null){
createInstance();
}
return instance;
}
Run Code Online (Sandbox Code Playgroud)
请注意一下synchronized.