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 Callable in 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 stringCallable that returns a string value.
  • Line 10: We submit the stringCallable to the executorService using the submit() method. The submit() method returns a Future.
  • Line 12: We retrieve the value of the Future obtained in line 10 using the get() method and print the result. (To learn more about the Future.get() method in Java, read this shot.)

Free Resources