How to execute a callable in the executor service
submit() is an instance method that takes a callable task as a parameter for execution and returns a Future.
Refer to What is the difference between runnable and callable in Java? to understand more about
Callablein Java.
Syntax
<T> Future<T> submit(Callable<T> task)
Parameters
Callable<T> task: The callable task to execute.
Return value
This method returns a Future.
Code
import java.util.concurrent.*;public class Main {public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executorService = Executors.newSingleThreadExecutor();Callable<String> stringCallable = () -> "Callable called";Future<String> callableFuture = executorService.submit(stringCallable);System.out.println("Result of the callable - " + callableFuture.get());executorService.shutdown();}}
Explanation
- Line 1: We import the relevant packages.
- Line 6: We define a single-threaded executor service called
executorService. - Line 8: We define a callable called
stringCallablethat returns a string value. - Line 10: We submit the
stringCallableto theexecutorServiceusing thesubmit()method. Thesubmit()method returns aFuture. - Line 12: We retrieve the value of the
Futureobtained in line 10 using theget()method and print the result. (To learn more about theFuture.get()method in Java, read this shot.)