How to wrap a runnable to return a non-null value using callable
Overview
callable() is a static method of the Executors class that takes a Runnable and a value as parameters. It returns a Callable when called, runs the passed Runnable task and returns the passed value.
Refer What is the difference between runnable and callable in Java? to understand the difference between
RunnableandCallable.
Syntax
public static <T> Callable<T> callable(Runnable task, T result)
Parameters
Runnable task: The runnable task to run.T result: The value/result to return.
Return value
This method returns a callable object.
Code
import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main {public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executorService = Executors.newSingleThreadExecutor();Runnable runnable = () -> System.out.println("Runnable executed");int resultToReturn = -234;Callable<Integer> callable = Executors.callable(runnable, resultToReturn);System.out.println("Return value - " + executorService.submit(callable).get());executorService.shutdown();}}
Explanation
- Lines 1-4: We import the relevant packages.
- Line 9: We create a single-threaded executor service.
- Line 10: We define a runnable task called
runnablethat prints a string. - Line 11: We define the result to return called
resultToReturn. - Line 11: Using the
callable()method we get a callable object passingrunnableandresultToReturnas arguments. - Line 12: We submit the callable to the executor service and print the result to the console.
- Line 13: We shut down the executor service.