我正在尝试将侦听器变成 Future,以进行异步连接。我还不习惯使用java futures,我对javascript Promise有一些经验,但我不知道如何用java编写它(我已经看到Java 8中的“CompletableFuture”可能会解决我的问题,不幸的是我卡住了java 7)。这是我到目前为止所做的:
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 commons 或 guava 等流行库中?)
终于从同事那里得到了答案。我正在寻找的内容存在于 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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)