Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
callable
runnable

How to wrap a runnable to return null using a callable in Java

abhilash

Overview

callable() is a static method of the Executors class that returns a Callable. When called, it runs the passed Runnable task and returns null.

Read What is the difference between runnable and callable in Java? to understand the difference between Runnable and Callable.

Syntax

public static Callable<Object> callable(Runnable task)
Syntax

Parameters

  • Runnable task: The runnable task to run.

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");
        Callable<Object> callable = Executors.callable(runnable);
        System.out.println("Return value - " + executorService.submit(callable).get());
        executorService.shutdown();
    }
}
Implementation of the callable() method

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 that prints a string.
  • Line 11: Using the callable() method, we get a Callable object passing the runnable defined in line 10 as the argument.
  • Line 12: We submit the Callable to the ExecutorService and print the result to the console. The result is null.
  • Line 13: We shut down the ExecutorService.

RELATED TAGS

java
communitycreator
callable
runnable
RELATED COURSES

View all Courses

Keep Exploring