可清除的单例对象获取类

public abstract class EnableCleanSingle<T>{

    private volatile T object;

    private int updateCount;

    public T getObject() {
        if(object == null) {
            synchronized (this){
                if(object == null) {
                    createObject();
                    updateCount++;
                }
            }
        }
        return object;
    }

    public void cleanObject(){
        int old = updateCount;
        if(object != null) {
            synchronized (this) {
                if (updateCount == old) {
                    object = null;
                }
            }
        }
    }

    abstract public T createObject();

}

猜你喜欢

转载自www.cnblogs.com/math-and-it/p/11404054.html
今日推荐