5
我試圖將偵聽器變成未來的異步連接。我不習慣使用java期貨,但我有一些JavaScript承諾的經驗,但我沒有看到如何寫在Java中(我已經看到Java 8中的「CompletableFuture」可以解決我的問題,不幸的是我卡住了Java 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中,或流行的庫,如Apache公用或番石榴?)
你能詳細說明你要實現的目標嗎? – 2014-10-30 11:29:27