r/javahelp • • Jun 02 '21

Codeless What is Future class in java?

I saw this class being used in a project recently, which was handling a parallel processing request. Please explain to me in layman terms what is the purpose of this class?

0 Upvotes

9 comments sorted by

View all comments

7

u/HecknChonker Extreme Brewer Jun 02 '21

Often times you want to be able to run multiple functions at the same time for performance reasons. A java process can spin up a child thread to run a function in a child thread to run that process, and then you can use a Future to pass the result of of that function from a child thread back to the the calling thread.

You can't pass the value back at the time you spin up the child thread because the value might not be ready yet. So instead java wraps the return value in a Future, and you can use that to access the value once it's ready. If you try to access the value before it's ready the main thread will wait until the child thread is finished processing, and then the main thread will continue again.


This is a the pattern I typically use.

public Future<Integer> countThings(List<Thing> things) {
    return CompletableFuture.supplyAsync(() -> {
        // Normally this would be doing something more complex than just returning the size of a list.
        // Like running a database query, calling an external API, or maybe downloading a file.

        // The value returned here will be passed back to the main thread via a Future.
        return things.size();
    });
}

And I would use it like this:

// This will create 2 background threads and start processing both.
Future<Integer> countOfThings = countThings(things);
Future<Integer> countOtherThings = countThings(otherThings);

// Other processing can continue to happen here on the main thread
// While this is happening, the two Future's are being processed in separate background threads until they return.

// When you call .get() on a future the main thread will wait until the background processing is complete.
// If the background processing finished before you call .get() the value will return immediately. 
Integer thingsCount = countOfThings.get();
Integer otherThingsCount = countOtherThings.get();

Let me know if this helps or if you have more questions.

1

u/General_C Jun 02 '21

Great explanation with an example. Thank you.