All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.centit.support.common.CachedObject Maven / Gradle / Ivy

There is a newer version: 5.3.2302
Show newest version
package com.centit.support.common;

import com.centit.support.algorithm.DatetimeOpt;

import java.util.Date;
import java.util.function.Supplier;

public class CachedObject {

    private T target;
    private boolean evicted;
    private Date refreshTime;
    private long freshPeriod;
    private Supplier refresher;

    public  CachedObject(Supplier refresher){
        this.target = null;
        this.evicted = true;
        this.refresher = refresher;
        //默认时间一个月
        this.freshPeriod = 43200L;
    }

    /**
     *
     * @param refresher 重新获取代码的接口
     * @param freshPeriod 保鲜时间,单位为分钟
     */
    public  CachedObject(Supplier refresher, long freshPeriod){
        this.target = null;
        this.evicted = true;
        this.refresher = refresher;
        this.freshPeriod = freshPeriod;
    }

    public void setFreshPeriod(int freshPeriod) {
        this.freshPeriod = freshPeriod;
    }

    public synchronized void evictObject(){
        evicted = true;
    }

    public synchronized T getCachedObject(){
        if(this.target == null || this.evicted ||
                System.currentTimeMillis() > refreshTime.getTime() + freshPeriod * 60000 ){
            target = refresher.get();
            refreshTime = DatetimeOpt.currentUtilDate();
            this.evicted = false;
        }
        return target;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy