Last Updated:

Java Callable. Brief description and example of use

Very often when working with threads, we need to get some result and it would be very convenient for the thread to return the results of its work. That is why the . It is very similar to the interface, but can return the result as an object and is capable of throwing exceptions.java.util.concurrent.CallableRunnableObject

The interface uses generics to determine the type of object to return. The Executors class provides useful methods for executing in a thread pool. Callable taskes return an object. Using Future we can find out the status of the Callable drag and get the returned object. This provides a method that waits for the Callable to complete to return a result.CallableCallablejava.util.concurrent.Futureget()

Future provides a method for canceling a Callable task. There is an overloaded version of the method where we can specify the time to wait for the result, this is necessary to avoid blocking the current stream for a long time. There are also methods and , that are used to obtain the status of an associated Callable task.cancel()get()isDone()isCancelled()

Here's a simple example of using a Callable task that returns the name of the thread. The example uses the Executor framework to run 100 tasks simultaneously and to get the result of the execution:Future

The result of the program execution (part of the output):

In the following articles, we will discuss and . Stay tuned.

Java FutureTaskScheduledThreadPoolExecutor