Thinking process

thinking about how to handle large amount of hits at same time

public class HitCounter {
    private Queue<Integer> queue;//<time>
    private HashMap<Integer, Integer> map; //<time, count>
    private int count;    

    private static final int TIME_LIMIT_IN_SECONDS = 300; // 5 minutes
    /** Initialize your data structure here. */
    public HitCounter() {
        count = 0;
        queue = new ArrayDeque<>();
        map = new HashMap<>();
    }

    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        //check map
        if (map.containsKey(timestamp)) {
            map.put(timestamp, map.get(timestamp) + 1);
        } else {
            queue.offer(timestamp);
            map.put(timestamp, 1);
        }

        //update count
        count++;
    }

    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    public int getHits(int timestamp) {
        //remove older hits
        while (!queue.isEmpty() && queue.peek() <= timestamp - TIME_LIMIT_IN_SECONDS) {
            int t = queue.poll();
            count -= map.get(t);
            map.remove(t);
        }

        //return
        return count;
    }
}

http://blog.gssxgss.me/not-a-simple-problem-rate-limiting/

results matching ""

    No results matching ""