Design a thread-safe Hit Counter

114 views Asked by At

I have designed a Hit Counter which can conveniently be used to design a Rate Limiter Original question: https://leetcode.com/problems/design-hit-counter/

To make it thread safe, I used lock statement.

public class HitCounter {
  private readonly int DURATION = 300;
  private readonly int[] hits, times;
  //https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock
  private readonly Object _lockObj = new Object();
  public HitCounter() {
    times = new int[DURATION];
    hits = new int[DURATION];
  }

  public void Hit(int timestamp) {
    var idx = timestamp % DURATION;
    lock (_lockObj){
      if(times[idx] != timestamp){
        times[idx] = timestamp;
        hits[idx] = 1;
      }else{
        hits[idx]++;
      }
    }
  }

  public int GetHits(int timestamp) {
    var res = 0;
    lock (_lockObj){
      for(var i = 0; i < DURATION; ++i){
        if(timestamp - times[i] < DURATION){
          res += hits[i];
        }
      }
    }
    return res;
  }
}

My questions are:

  • Is it just about surrounding the part which the two arrays are accessed with locks
  • Isn't it better to use ConcurrentDictionary as an index-array?

Any insight is appreciated.

0

There are 0 answers