番石榴Ratelimiter tryAcquire仅对第一次调用(任意数量的许可)返回true?

时间:2015-12-09 00:24:24

标签: java guava

我正在使用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

为什么会这样?

2 个答案:

答案 0 :(得分:7)

第一个例子的行为是预期的,因为:

// 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

来自番石榴文档:

  

返回的RateLimiter确保平均不超过   permitPerSecond在任何给定的秒内发出,持续   请求平稳分布在每一秒

第二个例子的行为也是预期的,因为要成功获得第二个“获取”的单一许可我们需要等待大约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的原因。

答案 1 :(得分:0)

如果您将应用程序睡眠1毫秒,它将返回true和true。