Last Updated:

Java FutureTask. Brief description and example of use

In the last lesson, we analyzed what is and how to use it effectively in your programs. Today we have Java in line: a small theory and an example of use.Java Collable FutureFutureTask

FutureTask is based on a specific interface implementation and provides asynchronous processing. It contains methods for starting and undoing a drag, as well as methods for getting the FutureTask status. We need a callable object to create a future drag, and then we can use the Java Thread Pool Executor for asynchronous processing.Future

Let's look at the example of a simple program.FutureTask

The following example shows commonly used methods in action:FutureTask

When we run the program above, it won't output anything to the console for a while. The thing is that the method of the class waits for the complete execution of the task and only then returns the object with the result of execution.get()FutureTask

There is also an overloaded method that only waits for a certain time – we used it for futureTask2.

Also note the use of the method that is used to verify that all tasks have completed successfully and that the program has completed.isDone()

The result of the program:

Be sure to check out Java Callable and stay tuned for updates in Multithreading and Concurrency in Java.