import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class TimestampThrottler {
private final int maxRequestsPerSecond;
private final ConcurrentLinkedQueue<Long> requestQueue = new ConcurrentLinkedQueue<>();
private final AtomicInteger requestCount = new AtomicInteger(0);
/**
* Constructor with maximum requests per second.
* @param maxRequestsPerSecond The maximum number of requests allowed per second.
*/
public TimestampThrottler(int maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
/**
* Adds a timestamp to the request queue, throttling requests.
* @param timestamp The timestamp to add.
*/
public void addRequest(long timestamp) {
// Wait if the request queue is full
while (requestQueue.size() >= maxRequestsPerSecond) {
try {
// Calculate how long to wait
long timeToWait = 1000 / maxRequestsPerSecond; // Milliseconds
Thread.sleep(timeToWait);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return; // Exit if interrupted
}
}
requestQueue.offer(timestamp);
}
/**
* Retrieves the next timestamp from the queue.
* @return The next timestamp, or -1 if the queue is empty.
*/
public long getNextTimestamp() {
if (!requestQueue.isEmpty()) {
return requestQueue.poll();
}
return -1; // Indicate queue is empty
}
public static void main(String[] args) throws InterruptedException {
int maxRequests = 5;
TimestampThrottler throttler = new TimestampThrottler(maxRequests);
for (int i = 0; i < 20; i++) {
long timestamp = System.currentTimeMillis() + i * 100;
throttler.addRequest(timestamp);
System.out.println("Added request: " + timestamp);
Thread.sleep(50); // Simulate some processing time
}
System.out.println("Processing requests...");
long nextTimestamp = throttler.getNextTimestamp();
while (nextTimestamp != -1) {
System.out.println("Processing timestamp: " + nextTimestamp);
nextTimestamp = throttler.getNextTimestamp();
}
System.out.println("All requests processed.");
}
}
Add your comment