【发布时间】:2014-04-10 13:58:19
【问题描述】:
我试图了解增量退避在 Java Couchbase API 中的工作原理。以下代码sn-p来自Couchbase Java Tutorial(我添加了几个cmets)。
public OperationFuture<Boolean> contSet(String key,
int exp,
Object value,
int tries) {
OperationFuture<Boolean> result = null;
OperationStatus status;
int backoffexp = 0;
try {
do {
if (backoffexp > tries) {
throw new RuntimeException("Could not perform a set after "
+ tries + " tries.");
}
result = cbc.set(key, exp, value);
status = result.getStatus(); // Is this a blocking call?
if (status.isSuccess()) {
break;
}
if (backoffexp > 0) {
double backoffMillis = Math.pow(2, backoffexp);
backoffMillis = Math.min(1000, backoffMillis); // 1 sec max
Thread.sleep((int) backoffMillis);
System.err.println("Backing off, tries so far: " + backoffexp);
}
backoffexp++;
// Why are we checking again if the operation previously failed
if (!status.isSuccess()) {
System.err.println("Failed with status: " + status.getMessage());
}
// If we break on success, why not do while(true)?
} while (status.getMessage().equals("Temporary failure"));
} catch (InterruptedException ex) {
System.err.println("Interrupted while trying to set. Exception:"
+ ex.getMessage());
}
if (result == null) {
throw new RuntimeException("Could not carry out operation.");
}
return result;
}
是否仅在操作成功或失败时才返回对getStatus() 的调用? (即同步)。 Java Tutorial 似乎说它正在阻塞,但 Java API 说:
获取此操作的当前状态。请注意,操作状态可能会随着对 NodeLocator 指定的服务器的尝试和可能重试操作而改变。
为什么我们需要多次检查status.isSuccess()?如果它成功了,我们就会跳出循环,我们可以假设它失败了?
如果有任何理由做while (status.getMessage().equals("Temporary failure"))而不是while(true),因为我们在状态成功时调用break?
谢谢
【问题讨论】: