1. import java.util.concurrent.ConcurrentLinkedQueue;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class TimestampThrottler {
  4. private final int maxRequestsPerSecond;
  5. private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>();
  6. private final AtomicInteger requestCount = new AtomicInteger(0);
  7. /**
  8. * Constructor with maximum requests per second.
  9. * @param maxRequestsPerSecond The maximum number of requests allowed per second.
  10. */
  11. public TimestampThrottler(int maxRequestsPerSecond) {
  12. this.maxRequestsPerSecond = maxRequestsPerSecond;
  13. }
  14. /**
  15. * Adds a timestamp to the request queue, throttling requests.
  16. * @param timestamp The timestamp to add.
  17. */
  18. public void addRequest(long timestamp) {
  19. // Wait if the request queue is full
  20. while (requestQueue.size() >= maxRequestsPerSecond) {
  21. try {
  22. // Calculate how long to wait
  23. long timeToWait = 1000 / maxRequestsPerSecond; // Milliseconds
  24. Thread.sleep(timeToWait);
  25. } catch (InterruptedException e) {
  26. Thread.currentThread().interrupt();
  27. return; // Exit if interrupted
  28. }
  29. }
  30. requestQueue.offer(timestamp);
  31. }
  32. /**
  33. * Retrieves the next timestamp from the queue.
  34. * @return The next timestamp, or -1 if the queue is empty.
  35. */
  36. public long getNextTimestamp() {
  37. if (!requestQueue.isEmpty()) {
  38. return requestQueue.poll();
  39. }
  40. return -1; // Indicate queue is empty
  41. }
  42. public static void main(String[] args) throws InterruptedException {
  43. int maxRequests = 5;
  44. TimestampThrottler throttler = new TimestampThrottler(maxRequests);
  45. for (int i = 0; i < 20; i++) {
  46. long timestamp = System.currentTimeMillis() + i * 100;
  47. throttler.addRequest(timestamp);
  48. System.out.println("Added request: " + timestamp);
  49. Thread.sleep(50); // Simulate some processing time
  50. }
  51. System.out.println("Processing requests...");
  52. long nextTimestamp = throttler.getNextTimestamp();
  53. while (nextTimestamp != -1) {
  54. System.out.println("Processing timestamp: " + nextTimestamp);
  55. nextTimestamp = throttler.getNextTimestamp();
  56. }
  57. System.out.println("All requests processed.");
  58. }
  59. }

Add your comment