我使用的是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为什么会发生这种情况?
发布于 2015-12-09 08:45:39
第一个示例的行为是预期的,因为:
// 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从Guava文档中:
返回的RateLimiter确保在任何给定的一秒钟内发出的平均不超过permitsPerSecond,并且持续的请求被平滑地散布在每一秒的上。
第二个示例的行为也是意料之中的,因为为了在第二个“获取”时成功获得单个许可,我们需要等待大约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的原因。
发布于 2016-08-27 09:03:08
如果您将应用程序休眠1毫秒,它将返回true和true。
https://stackoverflow.com/questions/34168675
复制相似问题