Which interface in Java is used to define a task that returns a result and can be executed by an ExecutorService?

Java MCQ: Which interface in Java is used to define a task that returns a result and can be executed by an ExecutorService?

a) Runnable
b) Callable
c) Executable
d) Task

Answer:

b) Callable

Explanation:

The Callable interface in Java is used to define a task that returns a result and can be executed by an ExecutorService. The Callable interface is part of the java.util.concurrent package and provides a call() method that must be implemented by the task. Unlike Runnable, which does not return a result, Callable allows you to return a result or throw an exception.

Here’s an example of using Callable:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable<String> task = () -> {
            return "Result from Callable";
        };

        Future<String> future = executor.submit(task);

        System.out.println("Task result: " + future.get());

        executor.shutdown();
    }
}

In this example, a Callable task is created that returns a string. The task is submitted to an ExecutorService, and a Future object is returned. The get() method of the Future object is used to retrieve the result of the task. The Callable interface is useful for tasks that need to return a result or can throw checked exceptions.

The Callable interface is often used in combination with ExecutorService to handle asynchronous tasks that require a result, making it a powerful tool for multithreaded programming in Java.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top