Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to wrap a runnable to return a non-null value using callable

abhilash

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 Runnable and Callable.

Syntax

public static <T> Callable<T> callable(Runnable task, T result)
Syntax

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();
    }
}
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 called runnable that prints a string.
  • Line 11: We define the result to return called resultToReturn.
  • Line 11: Using the callable() method we get a callable object passing runnable and resultToReturn as 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.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring