KeyCountWithExpiredTime.java 958 Bytes
package com.yoho.search.aop.downgrade;

import java.util.concurrent.atomic.AtomicInteger;

public class KeyCountWithExpiredTime {

    private AtomicInteger count;
    private long expiredTime;

    public KeyCountWithExpiredTime(long expiredTime){
        this.count = new AtomicInteger(0);
        this.expiredTime = expiredTime;
    }

    public int incrementAndGet(long newExpiredTime){
        //key已过期,过期时间设为newExpiredTime,count设为1
        if(this.expiredTime<System.currentTimeMillis()){
            this.resetExpiredTime(newExpiredTime);
        }else{
            this.count.incrementAndGet();
        }
        return this.count.get();
    }

    //线程安全
    private synchronized void resetExpiredTime(long newExpiredTime) {
        if (this.expiredTime < System.currentTimeMillis()) {
            this.expiredTime = newExpiredTime;
            this.count.set(1);
        }
    }

}