import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class UserRecordThrottler {
private final int maxRequestsPerSecond;
private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>();
private final AtomicInteger requestCount = new AtomicInteger(0);
public UserRecordThrottler(int maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
/**
* Attempts to process a user record request.
*
* @param userId The ID of the user.
* @return True if the request was allowed, false if throttled.
*/
public synchronized boolean allowRequest(long userId) {
// Check if we're exceeding the rate limit
if (requestCount.getAndIncrement() >= maxRequestsPerSecond) {
return false; // Throttle
}
// Add the request to the queue
requestQueue.offer(System.currentTimeMillis());
// Process the request (simulated here)
processRequest(userId);
return true;
}
private void processRequest(long userId) {
// Simulate processing the request. Replace with actual logic.
try {
// Simulate some work
Thread.sleep(10);
System.out.println("Processed request for user: " + userId);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupted state
System.err.println("Request processing interrupted: " + e.getMessage());
}
}
public static void main(String[] args) throws InterruptedException {
int maxRequests = 10; // Example: Allow 10 requests per second
UserRecordThrottler throttler = new UserRecordThrottler(maxRequests);
for (int i = 0; i < 20; i++) { // Simulate 20 requests
long userId = i;
if (throttler.allowRequest(userId)) {
System.out.println("Request " + userId + " allowed.");
} else {
System.out.println("Request " + userId + " throttled.");
}
Thread.sleep(50); // Simulate request intervals
}
}
}
Add your comment