Throttling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Throttler { private final long intervalInMillis; private long lastExecutionTime = 0; public Throttler(int maxCallsPerSecond) { if (maxCallsPerSecond <= 0) { throw new IllegalArgumentException("maxCallsPerSecond must be greater than zero."); } this.intervalInMillis = 1000L / maxCallsPerSecond; } public synchronized boolean allow() { long currentTime = System.currentTimeMillis(); if (currentTime - lastExecutionTime >= intervalInMillis) { lastExecutionTime = currentTime; return true; } return false; } } |