singleton完善写法
package com.june.study.design_pattens.singleton;
/**
* 写一个完美的还真不容易,感谢良葛格老师!
*
* 1. 实例的private性质和static性质
* 2. 构造器的private性
* 3. 如果是lazy-init的话,需要注意线程安全性
* 4. 看看线程安全性设计里,synchronized的位置;为什么判断两次instance==null呢!
*
* @author lijg fantaxy025025@126.com
* @date Feb 25, 2010 1:27:19 PM
* @version V3.0
*/
public class LazyThreadSafeSongleton {
private static LazyThreadSafeSongleton instance = null;
private LazyThreadSafeSongleton(){
//nothing here
}
/** 既然synchronized可以,lock也可以哦! */
public static LazyThreadSafeSongleton getInstance(){
if(instance == null){//one
synchronized (LazyThreadSafeSongleton.class) {//here!
if (instance == null) {//two
instance = new LazyThreadSafeSongleton();
}
}
}
return instance;
}
}
package com.june.study.design_pattens.singleton;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LazyThreadSafeSingleton2 {
private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
private static LazyThreadSafeSingleton2 instance = null;
private LazyThreadSafeSingleton2(){
//nothing here
}
/** 既然synchronized可以,lock也可以哦! */
public static LazyThreadSafeSingleton2 getInstance(){
if(instance == null){//one
reentrantReadWriteLock.writeLock().lock();
try {
if (instance == null) {
instance = new LazyThreadSafeSingleton2();
}
} catch (Exception e) {
//sth here
} finally{
reentrantReadWriteLock.writeLock().unlock();
}
}
return instance;
}
}
package com.june.study.design_pattens.singleton;
public class NormalSingleton {
private static NormalSingleton instance = new NormalSingleton();//here!
private NormalSingleton(){
//nothing here
}
public static NormalSingleton getInstance(){
return instance;
}
public static void main(String[] args) {
}
}