错误解法一:当处于多线程环境时,会出现竞争。
public class Singleton1 { private Singleton1() { } int a =5; private static Singleton1 singleton1 = null; public static Singleton1 getSingleton1(){ if(singleton1 == null){ singleton1 = new Singleton1(); } return singleton1; } }
错误解法二:虽然加了锁,解决了多线程下的竞争。但是在创建后的每次访问都加锁,影响效率。
public class Singleton2 { private Singleton2() { } int a =5; private static Singleton2 singleton2 = null; public static Singleton2 getSingleton2(){ synchronized(Singleton2.class) { if(singleton2 == null){ singleton2 = new Singleton2(); } } return singleton2; } }
可行的解法三:在锁前面再加一个if判断将是一种可行的解法。
public class Singleton3 { private Singleton3() { } int a =5; private static Singleton3 Singleton3 = null; public Singleton3 getSingleton3(){ if(Singleton3 == null){ synchronized(Singleton3.class) { if(Singleton3 == null){ Singleton3 = new Singleton3(); } } } return Singleton3; } }
推荐的解法4:利用静态构造函数
public class Singleton4 { private Singleton4() { } private static Singleton4 Singleton4 = new Singleton4(); public Singleton4 getSingleton4() { return Singleton4; } }
推荐的解法5:实现按需创建实例,涉及语言特性
public class Singleton5 { Singleton5() { } public Singleton5 getSingleton5() { return Nested.instance; } static class Nested{ Nested(){ } static Singleton5 instance = new Singleton5(); } }