有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

信号量java ScheduledFuture getDelay返回负值

我正在使用ScheduledExecutorService、信号量和ScheduledFuture编写一个速率限制函数,简单地说,当客户端达到限制时,服务器将返回错误429,并显示“msg请在%d秒后重试”。 我使用scheduledFuture。getDelay(TimeUnit.SECONDS)获取%d的值。对于第一次或第二次尝试,它的行为正常,即允许访问单元达到限制,并显示之后等待的秒数。然后getDelay开始显示负值。这是否意味着ScheduledExecutorService无法正常工作? 以下是片段

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);    
}

共 (0) 个答案