我的代码如下:这两个try...catch块太难看了。
我有两个请求,如果其中一个在超时期限内响应,我会将其添加到列表中,如果没有,我将向列表中添加一个null。
private List<String> getResult(Future future1, Future future2, long timeout) {
String resp1= null;
String resp2= null;
Stopwatch stopwatch = Stopwatch.createStarted();
try {
resp1= future1.get(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.error("req1 error", e);
}
// calculate the time remaining
long leftTime = timeout - stopwatch.elapsed(TimeUnit.MILLISECONDS);
if (leftTime > 0) {
try {
resp2 = future2.get(leftTime, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.error("req2 error", e);
}
}
ArrayList<String> results = Lists.newArrayListWithCapacity(2);
results.add(resp1);
results.add(resp2);
return results;
}发布于 2016-12-13 22:29:24
除了消除代码重复之外,您可以做的并不多;只需将代码移到它自己的方法中,例如:
private String getResultFromFuture(Future future, long timeout, String message) {
try {
return future.get(timeout, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.error(message, e);
}
return null;
}或者类似的东西;例如,还通过提供将结果添加到的列表;而不是返回它。
发布于 2016-12-13 22:45:21
您可以尝试这样的操作,并为两个Future对象调用它。
public void process(Future<String> f, int timeout, List<String> list) throws InterruptedException, ExecutionException{
try{
list.add(f.get(10000, TimeUnit.MILLISECONDS));
}catch (TimeoutException e) {
// add what you want
}
}https://stackoverflow.com/questions/41123446
复制相似问题