r/javahelp • u/akanshya9z12 • 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
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.
And I would use it like this:
Let me know if this helps or if you have more questions.