等待x毫秒或直到条件变为真
问题描述
我有一个代码,我将数据发送到队列,然后队列发回确认消息,告知他们已接收到数据,因此我要等待X倍的时间,然后再检查他们是否已接收到数据。下面是执行此操作的代码,它的工作原理是:
public boolean send(final long address, final byte[] records, final Socket socket) {
boolean sent = sendAsync(address, records, socket, true);
if (sent) {
try {
TimeUnit.MILLISECONDS.sleep(800);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
// if key is not present, then acknowledgement was received successfully
sent = !acknowledgementCache.asMap().containsKey(address);
// and key is still present in the cache, then it means acknowledgment was not received after
// waiting for timeout period, so we will remove it from cache.
if (!sent)
removeFromRetryBucket(address);
return sent;
}
上述代码现在的问题是-无论如何我都等待800 milliseconds
,那是错误的。确认可能会在100毫秒后返回,但我仍要等待800毫秒,因此我想在确认返回后立即返回,而不是等待那X的时间。
所以我想出了以下使用awaitility的代码,但由于某些原因,它无法按预期工作。意思是,即使确认很快返回,它仍然超时。我也尝试将超时值增加到很高的数值,但仍然超时,所以看起来有些错误。有没有更好的方法可以做到这一点?
public boolean send(final long address, final byte[] records, final Socket socket) {
boolean sent = sendAsync(address, records, socket, true);
if (sent) {
try {
// if key is not present, then acknowledgement was received successfully
Awaitility.await().atMost(800, TimeUnit.MILLISECONDS)
.untilTrue(new AtomicBoolean(!acknowledgementCache.asMap().containsKey(address)));
return true;
} catch (ConditionTimeoutException ex) {
}
}
// and key is still present in the cache, then it means acknowledgment was not received after
// waiting for timeout period, so we will remove it from cache.
removeFromRetryBucket(address);
return false;
}
注意:到目前为止,我正在使用Java 7。我确实可以使用番石榴,所以如果除了等候能力之外还有什么更好的选择,那么我也可以使用它。
解决方法:
为了能够在Java 7中检查您需要编写一个可调用对象。
@Test
public void send() {
//when
boolean sent = sendAsync(address, records, socket, true);
//then
if (sent) {
await().until(receivedPackageCount(), equalTo(false));
}
}
private Callable receivedPackageCount(String address) {
return new Callable() {
@Override
public boolean call() throws Exception {
return acknowledgementCache.asMap().containsKey(address);
}
};
}
必须与上面类似。可能会有编译错误,因为我写的不是ide。