package cn.axzo.msg.center.message.service.todo.cache;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author yanglin
 */
class PeriodCacheMetric {

    private final String name;
    private final AtomicReference<CacheMetric> metric;

    PeriodCacheMetric(String name, int period, TimeUnit timeUnit) {
        this.name = name;
        this.metric = new AtomicReference<>(new CacheMetric(name));
        Executors.newSingleThreadScheduledExecutor()
                .scheduleAtFixedRate(this::printAndReset, period, period, timeUnit);
    }

    void incrHitCount() {
        metric.get().incrHitCount();
    }

    void incrMissCount() {
        metric.get().incrMissCount();
    }

    void printAndReset() {
        CacheMetric nextPeriod = new CacheMetric(name);
        CacheMetric prevPeriod = this.metric.getAndSet(nextPeriod);
        prevPeriod.print();
    }

}