【发布时间】:2019-03-02 11:32:05
【问题描述】:
我正在使用ScheduledExecutorService、Semaphore 和ScheduledFuture 编写一个限速函数,简单来说,当客户端达到限制时,服务器会返回错误429 并显示“msg please try after %d second”。 我使用 scheduleFuture.getDelay(TimeUnit.SECONDS) 来获取 %d 的值。对于第一次或第二次尝试,它表现正常,即允许访问单元达到限制并显示之后等待多少秒。然后 getDelay 开始显示负值。这是否意味着 ScheduledExecutorService 无法正常工作? 以下是sn-p
public RateLimiter(int permits, long durationInMillis){
this.semaphore = new Semaphore(permits);
this.permits = permits;
this.durationInMillis = durationInMillis;
scheduleReplenishment();
}
public boolean allowAccess() {
return semaphore.tryAcquire();
}
public long nextReplenishmentTime() {
return scheduledFuture.getDelay(TimeUnit.SECONDS);
}
public void stop() {
scheduler.shutdownNow();
}
public void scheduleReplenishment() {
scheduledFuture = scheduler.schedule(() -> {
semaphore.release(permits - semaphore.availablePermits());
}, durationInMillis, TimeUnit.MILLISECONDS);
}
【问题讨论】:
标签: java semaphore scheduledexecutorservice