I am trying to turn the listener into the Future, for an asynchronous connection. I’m not used to using java futures yet, I have some experience with javascript promises, but I don’t see how to write it in java (I saw that “CompletableFuture” in Java 8 can solve my problem, unfortunately, I'm stuck since java 7). Here is what I have done so far:
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(); } } }
I cannot find an easy way to do this. The only solution I have found so far is the FutureTask extension and at the end of the Callable run, wait / hibernate until a specific state variable is set. I don't really like the idea of ​​waiting / sleeping in my business code, maybe there is something that already exists to make it delayed? (in java or popular libraries like Apache or guava?)
source share