Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What Does java.util.concurrent.Future Hold?

DZone's Guide to

What Does java.util.concurrent.Future Hold?

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Arun Manivannan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}