September 16, 2012 · concurrency

What does java.util.concurrent.Future hold?

Let's be sure of what the Future holds

Future, which is a part of the Java concurrency Task execution framework, is the result of your computation as the javadoc claims. And more.

When you are executing a task in a different thread, there is a lot of information you would need from it soon after you submit it to the pool.

What can the Future give?

  1. Result : If you are spawning multiple threads and you are interested in the consolidated/incremental result, obviously you wanted a way to get it. So, here you go. Future.get()

  2. Cancel : Just in case if you spawned 10 threads and you are happy with just one result and wanted to kill the others (or) you wanted to kill that rogue thread (or) you simply loved to power to cancel any thread at will, you have a nice Future.cancel().

  3. Status : Future.isDone() is your way of asking Are you done with your work?

Interesting fact :

The Future.get() method waits for the result forever until the result gets returned. For some cases, you might need this. However, if you don't want to wait forever, you might choose the overloaded get method

V get(long timeout, TimeUnit unit)

Fun Fact :

If you are just spawning a single thread in your Executor and calling the Future.get() (the one which waits forever), you are actually mimicking a Thread.join() call on a spawned single thread by the main thread.

Further reading :