Arun is a curious programmer who has spent the last 9 years trying to create better and faster programs. When the sun goes down, he experiments with various technologies and programming languages. He blogs at http://rerun.me. Arun is a DZone MVB and is not an employee of DZone and has posted 21 posts at DZone. You can read more from them at their website. View Full User Profile

What Does java.util.concurrent.Future Hold?

09.25.2012
| 5791 views |
  • submit to reddit
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 :

Future.get() blocks

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 :

Alex Miller’s amazing blog

Alex Miller’s concurrency gotchas

Vogella’s article on comparison with original API

Good introduction to concurrency in general

Highly recommended book on Java concurrency

Published at DZone with permission of Arun Manivannan, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)