Shrreya Behll
Shrreya Behll

Reputation: 195

What is the difference between future and promise in vertx?

I usually see the use of either promise and future in the start of a vert.x verticle. Is there any specific difference between both? I have read about their differences in Scala language, is it the same in case of Vert.x too? Also when should I know when to use promise or a future?

Upvotes: 19

Views: 11579

Answers (5)

Tcheutchoua Steve
Tcheutchoua Steve

Reputation: 556

As a paraphrase,

A future is a read-only container for a result that does not yet exist, while a promise can be written (normally only once).

More from here

Upvotes: 0

Woody
Woody

Reputation: 8002

A bit late to the game, and the other answers say as much in different words, however this might help. Lets say you were wrapping some older API (e.g. callback based) to use Futures, then you might do something like this :

Future<String> getStringFromLegacyCallbackAPI() {
   Promise<String> promise = Promise.promise();
   legacyApi.getString(promise::complete);
   return promise.future();
}

Note that the person who calls this method gets a Future so they can only specify what should happen in the event of successful completion or failure (they cannot trigger completion or failure). So, I think you should not pass the promise up the stack - rather the Future should be handed back and the Promise should be kept under the control of the code which can resolve or reject it.

Upvotes: 4

Rogelio Trivi&#241;o
Rogelio Trivi&#241;o

Reputation: 6519

The best I've read about:

think on Promise as producer (used by producer on one side of async operation) and Future as consumer (used by consumer on the other side).

Futures vs. Promises

Upvotes: 8

mononoke83
mononoke83

Reputation: 451

A Promise as well is a writable side of an action that may or not have occurred yet. And according to the wiki :

Given the new Promise / Future APIs the start(Future<Void>) and stop(Future<Void>) methods have been deprecated and will be removed in Vert.x 4.

Please migrate to the start(Promise) and stop(Promise) variants.

Upvotes: 0

Veeresh Devireddy
Veeresh Devireddy

Reputation: 1145

Promise are for defining non-blocking operations, and it's future() method returns the Future associated with a promise, to get notified of the promise completion and retrieve its value. The Future interface is the result of an action that may, or may not, have occurred yet.

Upvotes: 6

Related Questions