我正在使用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
来自番石榴文档:
返回的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
.