将Java中的监听器转换为Future

7

我正在尝试将监听器转换为Future,以进行异步连接。我不习惯使用Java Future,但我有一些使用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?)


你能详细说明一下你想要实现什么吗? - Muli Yulzary
1个回答

6

我终于从同事那里得到了答案。我需要的东西在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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接