1. import java.util.concurrent.ConcurrentLinkedQueue;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class UserRecordThrottler {
  4. private final int maxRequestsPerSecond;
  5. private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>();
  6. private final AtomicInteger requestCount = new AtomicInteger(0);
  7. public UserRecordThrottler(int maxRequestsPerSecond) {
  8. this.maxRequestsPerSecond = maxRequestsPerSecond;
  9. }
  10. /**
  11. * Attempts to process a user record request.
  12. *
  13. * @param userId The ID of the user.
  14. * @return True if the request was allowed, false if throttled.
  15. */
  16. public synchronized boolean allowRequest(long userId) {
  17. // Check if we're exceeding the rate limit
  18. if (requestCount.getAndIncrement() >= maxRequestsPerSecond) {
  19. return false; // Throttle
  20. }
  21. // Add the request to the queue
  22. requestQueue.offer(System.currentTimeMillis());
  23. // Process the request (simulated here)
  24. processRequest(userId);
  25. return true;
  26. }
  27. private void processRequest(long userId) {
  28. // Simulate processing the request. Replace with actual logic.
  29. try {
  30. // Simulate some work
  31. Thread.sleep(10);
  32. System.out.println("Processed request for user: " + userId);
  33. } catch (InterruptedException e) {
  34. Thread.currentThread().interrupt(); // Restore interrupted state
  35. System.err.println("Request processing interrupted: " + e.getMessage());
  36. }
  37. }
  38. public static void main(String[] args) throws InterruptedException {
  39. int maxRequests = 10; // Example: Allow 10 requests per second
  40. UserRecordThrottler throttler = new UserRecordThrottler(maxRequests);
  41. for (int i = 0; i < 20; i++) { // Simulate 20 requests
  42. long userId = i;
  43. if (throttler.allowRequest(userId)) {
  44. System.out.println("Request " + userId + " allowed.");
  45. } else {
  46. System.out.println("Request " + userId + " throttled.");
  47. }
  48. Thread.sleep(50); // Simulate request intervals
  49. }
  50. }
  51. }

Add your comment