2016-12-13 8 views
1

Mycode는 다음과 같습니다. 두 개의 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; 
} 

답변

1

너무 많이 할 수는 없습니다. 코드 복제를 제거하는 것 외에; 그 코드를 다음과 같이 간단하게 자신의 메서드로 옮김으로써 :

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

또는 무엇인가; 예를 들어 결과가 추가 된 목록을 제공함으로써; 그것을 돌려주는 대신에.

0

다음과 같이 두 개의 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 
       } 


}