Sridhar Sarnobat
Sridhar Sarnobat

Reputation: 25236

Java futures - eager execution?

I was reading about Futures as a clean way of asynchronously executing tasks, and at one point recall that it said that the task doesn't get executed unless you read the return value from the Future (in an attempt to replicate lazy evaluation perhaps). I have a feeling this is not accurate.

Could someone clarify whether this really is true?

What if you want to execute some asynchronous logic without wanting to read its return value? (e.g. a write to a database as I'm doing in my application)

Upvotes: 1

Views: 394

Answers (1)

mambax
mambax

Reputation: 1117

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

Future is to wait for a result. The future object holds a reference to a later availbable result. The call for a Future immedatelym returns, allowing you to continue in your code and not busy waiting for an answer.

If you just want to execute asynchronous not waiting for a result you can use either Threads, or in your case maybe Executors (or ExecutorServices).

Executor

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.

ExecutorService extends the Executor for some control functionality.

Upvotes: 1

Related Questions