Mike W
Mike W

Reputation: 1148

Do I need to do a future.get() on a Future that doesn't return a value that I care about?

My Java app uses a java.util.concurrent.Executors.newCachedThreadPool() to launch a number of different threads that do different kinds of work.

Some of the threads return a value. For these, I am using Future.get() to retrieve the value from the thread.

Other threads don't return a value that I care about. They are declared to return an Object, and the returned value is always null. For these threads, I am currently calling Future.get() even though there is no value to get. Is that necessary, or is it pointless? My thinking was that perhaps Future.get() notifies the thread pool that I'm done with this thread.

Upvotes: 1

Views: 2687

Answers (3)

user949300
user949300

Reputation: 15729

Short answer is no. However, if you want to check that everything completed successfully, Future.get() will let you know if there was an ExecutionException (by throwing it). So I usually call it, even if there is no "result" that I care about. YMMV depending on how you are doing the error handling.

As Tom Anderson mentions, Callable<Void> is an option to remind people that there is no "result". But frankly, my Callables meant for an Executor almost always return themselves, so that you can really double check on the results if need be. e.g. (somewhat exaggerated)

public class LongCalculation implements Callable<LongCalculation> {

   public double getResult() { ... }
   public SomeEnum getStatus() { ... } // e.g. FAILED, SUCCESS, CANCELLED
   public List<String> getAnythingWeirdThatHappenned() { ... }
}

Upvotes: 1

yorkw
yorkw

Reputation: 41126

Nothing wrong with calling Future.get() on callable task that returns null. Bear in mind that Future.get() block calling thread execution. by doing that, you indeed make the worker thread running synchronously with the calling thread. As it's name stated, Future.get() is get something from future, hence calling thread need wait.

Upvotes: 1

Tom Anderson
Tom Anderson

Reputation: 47243

As far as i know, the documentation is silent on the matter. But that means there's nothing saying you do need to do that. It would be pretty weird if you did need to - it would be very easy to accidentally screw up a thread pool by forgetting to.

As an aside, a popular choice for these return-nothing Callables is Callable<Void>. Void is an uninstantiable placeholder class, so it's a good choice for variables which will only ever be null.

Upvotes: 0

Related Questions