Java 是否有一种优雅的方式在指定的超时时间内处理多个期货?

Java 是否有一种优雅的方式在指定的超时时间内处理多个期货?,java,java.util.concurrent,Java,Java.util.concurrent,Mycodes如下:两个try…catch块太难看了 我有两个请求,如果有一个响应在超时时间内,我会将其添加到列表中,如果没有,我会将null添加到列表中 private List<String> getResult(Future future1, Future future2, long timeout) { String resp1= null; String resp2= null; Stopwatch stopwatch = Stopwatch.cre

Mycodes如下:两个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;
}
private List getResult(Future future1、Future future2、长超时){
字符串resp1=null;
字符串resp2=null;
Stopwatch Stopwatch=Stopwatch.createStarted();
试一试{
resp1=future1.get(超时,时间单位为毫秒);
}捕获(例外e){
记录器错误(“req1错误”,e);
}
//计算剩余时间
long leftTime=超时-秒表已用时间(时间单位为毫秒);
如果(leftTime>0){
试一试{
resp2=future2.get(leftTime,TimeUnit.ms);
}捕获(例外e){
记录器错误(“请求2错误”,e);
}
}
ArrayList results=Lists.newArrayList WithCapacity(2);
结果:添加(resp1);
结果:添加(resp2);
返回结果;
}

你能做的不多;除消除代码重复外;只需将代码移动到自己的方法中,如:

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;
}

或者类似的东西;例如,还提供一个添加结果的列表;而不是返回它。

您可以尝试类似的方法,并为未来的两个对象调用它

    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
                }


}
public void进程(Future f、int timeout、List List)抛出InterruptedException、ExecutionException{
试一试{
添加(f.get(10000,时间单位毫秒));
}捕获(超时异常e){
//添加您想要的内容
}
}