+-
java – Guava Ratelimiter tryAcquire仅对第一次调用(任意数量的许可)返回true?
我正在使用Guava 18.0 RateLimiter:

public static void simpleTst() throws Exception{
    RateLimiter lt = RateLimiter.create(2);
    _log.info("Acquired one " + lt.tryAcquire());
    _log.info("Acquired two " + lt.tryAcquire());
}

输出是:

: 08 16:22:10 PST.INFO1*RateLimiterTst~simpleTst@37: Acquired one true
: 08 16:22:10 PST.INFO1*RateLimiterTst~simpleTst@38: Acquired two false

将许可证数量指定为12:

public static void simpleTst() throws Exception{
    RateLimiter lt = RateLimiter.create(2);
    _log.info("Acquired one " + lt.tryAcquire(12));
    _log.info("Acquired two " + lt.tryAcquire());
}

输出是:

: 08 16:22:36 PST.INFO1*RateLimiterTst~simpleTst@37: Acquired one true
: 08 16:22:36 PST.INFO1*RateLimiterTst~simpleTst@38: Acquired two false

为什么会这样?

最佳答案
预期第一个示例的行为是因为:

// we request 2 permit per seconds
RateLimiter lt = RateLimiter.create(2);
_log.info("Acquired one " + lt.tryAcquire());

// waiting 1/2 second we will be able to get the second permit
Thread.sleep(500);
_log.info("Acquired two " + lt.tryAcquire());

输出是:

Acquired one true
Acquired two true

来自番石榴文档:

The returned RateLimiter ensures that on average no more than
permitsPerSecond are issued during any given second, with sustained
requests being smoothly spread over each second.

第二个例子的行为也是预期的,因为要成功获得第二个“获取”的单一许可我们需要等待大约6秒(= 12/2)

// we request 2 permit per seconds
RateLimiter lt = RateLimiter.create(2);

// trying to acquire 12 permits
_log.info("Acquired one " + lt.tryAcquire(12));

// waiting 12 / 2 seconds in order to be able to get the second permit
Thread.sleep(6000);
_log.info("Acquired two " + lt.tryAcquire());

输出是:

Acquired one true
Acquired two true

尝试获取等待时间少于6秒的最后一个许可证将失败,这就是为什么示例中的lt.tryAcquire()返回false.

点击查看更多相关文章

转载注明原文:java – Guava Ratelimiter tryAcquire仅对第一次调用(任意数量的许可)返回true? - 乐贴网