Turning the listener into the future in java

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?)

+5
source share
1 answer

I finally got my answer from a colleague. What I'm looking for exists in Guava: SettableFuture. This is what 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; 
+5
source

Source: https://habr.com/ru/post/1205851/


All Articles