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

org.mydotey.util.CounterBucket Maven / Gradle / Ivy

The newest version!
package org.mydotey.util;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;

/**
 * @author koqizhao
 *
 * Jul 25, 2018
 */
public class CounterBucket extends TimeBucket {

    protected static final Function COUNTER_CREATOR = k -> new AtomicLong();

    private final ConcurrentHashMap _counters;

    public CounterBucket(long startTime, long ttl) {
        super(startTime, ttl);
        _counters = new ConcurrentHashMap();
    }

    public long get(T identity) {
        Objects.requireNonNull(identity, "identity is null");
        AtomicLong counter = _counters.get(identity);
        return counter == null ? 0 : counter.get();
    }

    public void increment(T identity) {
        Objects.requireNonNull(identity, "identity is null");
        AtomicLong counter = getCounter(identity);
        counter.incrementAndGet();
    }

    public void decrement(T identity) {
        Objects.requireNonNull(identity, "identity is null");
        AtomicLong counter = getCounter(identity);
        counter.decrementAndGet();
    }

    private AtomicLong getCounter(T identity) {
        return _counters.computeIfAbsent(identity, COUNTER_CREATOR);
    }

    @Override
    public void reset(long startTime) {
        super.reset(startTime);
        _counters.clear();
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy