Turning a listener into a future in java

旧城冷巷雨未停 提交于 2019-12-05 07:54:05

I finally got my answer from a colleague. What I'm looking for exists in Guava: SettableFuture. Here's how the code looks like:

    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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!