下面的Java代码给出了单例模式的四种不同设计,在多线程的实际环境测试下会表现出不同的效果,请对这几种设计完成分析评价。
//设计1 class STon { private static instance =null; public static STon getInstance() { if (instance == null) synchronized(singleton.class) { if (instance == null ) { instance == new STon; } } return instance; } } | //设计2 class STon { private static instance =null; public synchronized static STon getInstance() { if (instance == null ) instance == new STon; return instance; } } |
//设计3 class STon { private static instance =null; public static STon getInstance() { if (instance == null ) instance == new STon; return instance; } } | //设计4 class STon { private static instance = new STon; public static STon getInstance() { return instance; } } |
设计1、2、4均可,设计3有线程安全问题,多线程并发时可能会出问题;
设计1双重检查,第一个判断instance是否为null避免了已有对象时的排队阻塞;
设计2全局锁直接让每次访问都互斥,性能不佳;
设计3存在线程安全问题,判断null和创建之间可能被打断(如中断、异常等等);
设计4贪心法,对象唯一创建后常驻内存,对内存消耗较大。