Tharanga
Tharanga

Reputation: 387

How Future works in Vert.x?

I send a message using EventBus and i want to get the reply message into a variable then will return it.this is the code block.

public class MessageExecute {

private static final Logger logger = LoggerFactory.getLogger(MessageExecute.class);

public static <T> T sendMessage(Vertx vertx,String address,T message){

    Future<Message<T>> future = Future.future();

    vertx.eventBus().send(address, message, future.completer());

    future.setHandler(new Handler<AsyncResult<Message<T>>>() {

        @Override
        public void handle(AsyncResult<Message<T>> event) {
            logger.info("received reply message | thread - " + Thread.currentThread().getName());
        }

    });
    boolean notFound = true;
    while(notFound){
        try{
            if(future.result()!= null){
                notFound = false;
            }
        }catch(Exception e){

        }
    }


    return message;

 }
}

Actually this is working fine.But some times While block never exit.Its mean future.result() not getting the value ,even after the reply message is received.I don't know this the correct way and I don't have clear idea about how the Futures work in vert.x .Is there any other way to implement these kind of scenario.

Upvotes: 2

Views: 7626

Answers (1)

Luiz H. Rapat&#227;o
Luiz H. Rapat&#227;o

Reputation: 84

I recommend you to read about the Vertx-Sync project - http://vertx.io/docs/vertx-sync/java/

In examples, have the follow example that appears very similar to you case:

EventBus eb = vertx.eventBus();
HandlerReceiverAdaptor<Message<String>> adaptor = streamAdaptor();
eb.<String>consumer("some-address").handler(adaptor);
// Receive 10 messages from the consumer:
for (int i = 0; i < 10; i++) {
    Message<String> received1 = adaptor.receive();
    System.out.println("got message: " + received1.body());
}

Upvotes: 1

Related Questions