2014-10-30 2 views
5

비동기 연결을 위해 수신기를 Future로 전환하려고합니다. 아직 자바 선물을 사용하는 데 익숙하지 않은, 나는 자바 스크립트 약속과 함께 몇 가지 경험을 가지고 있지만 자바 ("CompletableFuture"자바 8 내 문제를 해결할 수 있습니다 본 적이 자바에서 그것을 작성하는 방법을보고 실패, 불행히도 나는 자바 7 붙어). 여기에 지금까지 한 일이다 : 나는 그것을 할 수있는 쉬운 방법을 찾을 수 없습니다청취자를 Java로 미래로 변환

public Future<Boolean> checkEmailClientConfiguration(final EmailClientConfiguration config) { 
    final Future<Boolean> future = ???; 
    // In some other languages I would create a deferred 
    Transport transport = null; 
    try { 
     transport = session.getTransport("smtp"); 
     transport.addConnectionListener(new ConnectionListener() { 
      @Override 
      public void opened(ConnectionEvent connectionEvent) { 
       System.out.println("!!!opened!!! ; connected=" + ((SMTPTransport) connectionEvent.getSource()).isConnected()); 
       // HERE I would like to make my future "resolved" 
      } 

      @Override 
      public void disconnected(ConnectionEvent connectionEvent) { 
      } 

      @Override 
      public void closed(ConnectionEvent connectionEvent) { 
      } 
     }); 
     transport.connect(config.getMailSMTPHost(), 
          config.getMailSMTPPort(), 
          config.getMailUsername(), 
          config.getMailPassword()); 
     return future; 
    } catch (final MessagingException e) { 
     throw e; 
    } finally{ 
     if(transport != null){ 
      transport.close(); 
     } 
    } 
} 

. 지금까지 발견 한 유일한 해결책은 FutureTask를 확장하고 Callable 실행이 끝날 때 일부 상태 변수가 해결 될 때까지 대기/절전입니다. 비즈니스 코드에서 기다리거나 잠자는 아이디어가 정말 마음에 들지 않습니다. 이미 지연된 것을 만들기 위해 이미 존재하는 것이 있습니까? (Java에서 또는 아파치 공유지 또는 구아바와 같은 대중적인 라이브러리에서)

+0

달성하려는 작업을 자세히 설명 할 수 있습니까? –

답변

5

나는 동료에게서 나의 대답을 마침내 얻었다. 내가 찾고있는 것은 Guava에 존재합니다 : SettableFuture. 코드의 모양은 다음과 같습니다.

final SettableFuture<Boolean> future = SettableFuture.create(); 
    Transport transport = null; 
    try { 
     transport = session.getTransport("smtp"); 
     transport.addConnectionListener(new ConnectionListener() { 
      @Override 
      public void opened(ConnectionEvent connectionEvent) { 
       future.set(((SMTPTransport) connectionEvent.getSource()).isConnected()); 
      } 

      @Override 
      public void disconnected(ConnectionEvent connectionEvent) { 
      } 

      @Override 
      public void closed(ConnectionEvent connectionEvent) { 
      } 
     }); 
     transport.connect(config.getMailSMTPHost(), 
       config.getMailSMTPPort(), 
       config.getMailUsername(), 
       config.getMailPassword()); 
    } catch (final MessagingException e) { 
     future.setException(e); 
    } finally{ 
     if(transport != null){ 
      transport.close(); 
     } 
    } 
    return future;