-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRateLimiter.java
More file actions
46 lines (35 loc) · 1.16 KB
/
Copy pathRateLimiter.java
File metadata and controls
46 lines (35 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.stacktips.designpatterns.singleton;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
class RateLimiter {
private static RateLimiter instance;
private Map<String, Queue<Integer>> userRequests;
private static final int MAX_REQUESTS_PER_MINUTE = 3;
private RateLimiter() {
userRequests = new HashMap<>();
}
public static RateLimiter getInstance() {
if (instance == null) {
synchronized (RateLimiter.class) {
if (instance == null) {
instance = new RateLimiter();
}
}
}
return instance;
}
public synchronized boolean allowRequest(int timestamp, String userId) {
int currentMinute = timestamp / 60;
Queue<Integer> requests = userRequests.computeIfAbsent(userId, k -> new LinkedList<>());
while (!requests.isEmpty() && requests.peek() / 60 < currentMinute) {
requests.poll();
}
if (requests.size() < MAX_REQUESTS_PER_MINUTE) {
requests.offer(timestamp);
return true;
}
return false;
}
}