Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Callable Interface in Java?
3.
Why use a Callable interface in Java?
4.
Return Value of Callable Interface in Java
5.
Syntax of Callable Interface
6.
Implementation of Callable Interface
6.1.
Java
6.2.
Explanation:
7.
Features of Callable Interface
8.
Runnable Interface in Java
8.1.
Limitations of Runnable Interface in Java
9.
Frequently Asked Questions
9.1.
What is Java Callable interface?
9.2.
How do you implement the Callable interface in Java?
9.3.
What is the difference between Callable interface and runnable interface in Java?
9.4.
When should we use Callable Java?
9.5.
What is the difference between Callable and future in Java?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Callable Interface in Java

Author Sagar Mishra
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In Java programming, the Callable interface stands as a powerful tool for managing concurrent tasks with precision. Unlike its counterpart, the Runnable interface, Callable allows tasks to return results or throw exceptions, opening doors to enhanced control and error handling in multithreaded environments.

Callable Interface in Java

This blog will discuss the topic of the callable interface in Java. So, let's move to the topic without wasting time.

What is a Callable Interface in Java?

The Callable interface in Java lets you run a class instance as a thread by implementing it. It's found in the java.util.concurrent package. With Callable, your thread can return any object as a result and handle exceptions smoothly.

The method call() in the callable interface can return anything using the generics.

Related article - Difference between Callable and Runnable

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why use a Callable interface in Java?

In Java, the Callable interface is used primarily for its role in concurrent programming. It's part of the java.util.concurrent package and provides a way to execute tasks asynchronously and retrieve their results.

The main advantage of using Callable over Runnable is that Callable tasks can return a result and throw exceptions, while Runnable tasks cannot. This makes Callable especially useful in scenarios where you need to execute tasks in parallel and obtain their computed values or handle exceptions that may occur during execution.

When working with multi-threading, thread pools, or asynchronous programming in Java, Callable allows for better error handling and result retrieval, making it a valuable tool for building efficient and robust concurrent applications.

Return Value of Callable Interface in Java

The Callable interface in Java returns a value of a specified type when a task is executed. Unlike Runnable, which doesn't return any value, Callable's call() method can return a result or throw an exception. This feature is particularly useful in concurrent programming when you need to perform tasks asynchronously and obtain computed results or handle exceptions, making it a valuable choice for many multi-threading scenarios.

Syntax of Callable Interface

The syntax of the callable interface is as follows:

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}


Here, V is a generic return type of the callable interface. We can use the callable interface just by overriding the call() method, and then we can write the logic inside the method.

Also see,  Swap Function in Java

Implementation of Callable Interface

We have discussed the definition, syntax and features of the callable interface. Now, we will see how to implement this.

  • Java

Java

import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;

public class NinjaTest implements Callable<String> {

   @Override
   public String call() throws Exception {
       Thread.sleep(50);
       // Return the current thread
       return Thread.currentThread().getName();
   }
   // Main method
   public static void main(String args[]){
       ExecutorService executor = Executors.newFixedThreadPool(5);
      
       // Creating a list for the Future object
       List<Future<String>> list = new ArrayList<Future<String>>();
      
       // Creating an instance named NinjaTest
       Callable<String> callable = new NinjaTest();

       for(int i = 0; i < 10; i++){
           Future<String> future = executor.submit(callable);
           list.add(future);
       }
      
       for(Future<String> fut : list){
           try {
               // Print the return value of Future
               System.out.println(fut.get());
           } catch (InterruptedException | ExecutionException e) {
               e.printStackTrace();
           }
       }
      
       executor.shutdown();
   }
}


Output:

pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-3
pool-1-thread-1
pool-1-thread-5
pool-1-thread-2
pool-1-thread-4


Explanation:

In the above example,

  • We have created an object of ExecutorService in the main method inherited from the Executors utility class.
     
  • Next, we have created a list variable of list type to hold the object of the Future associated with Callable.
     
  • In the next step, we created an instance NinjaTest using the Callable class.
     
  • Inside the for loop, we have submitted the Callable tasks that will be executed by the thread pool using the submit() method.
     
  • We will add the Future to the list and receive a return value using Future.
     
  • We will print the return value inside the for loop under the try block. Here, you can notice the delay time. The compiler will delay because Future.get() waits for the task to get completed.
     
  • At last, we will shut down the executor.

Features of Callable Interface

There are many features of the callable interface. Let's discuss them.

  • The entire code for the callable class is present in the single function "call()".
     
  • The callable class is a SAM (Single Abstract Method) type interface and can be executed in a lambda expression.
     
  • A callable interface's call() method can return any type of object.
     
  • The get() function in the callable interface is also known as the blocking call, and it keeps blocking till the computation is finished.
     
  • The FutureTask object's cancel() method can stop the computation also.

Runnable Interface in Java

The Runnable interface in Java serves as a fundamental building block for implementing multithreading in Java applications. It provides a simple and efficient way to define tasks that can be executed concurrently within a program. By implementing the run() method defined in the Runnable interface, developers can encapsulate the code to be executed by a thread.

Limitations of Runnable Interface in Java

However, despite its usefulness, the Runnable interface does come with certain limitations:

  • Inability to Return Values: One of the primary limitations of the Runnable interface is its inability to return values or throw checked exceptions. The run() method, which is the only method in the interface, has a void return type. This makes it challenging to retrieve results or handle exceptions that occur during the execution of a thread.
  • Limited Error Handling: Runnable tasks executed by threads cannot throw checked exceptions directly. Instead, developers must handle exceptions within the run() method or propagate unchecked exceptions, which can lead to less robust error handling mechanisms.
  • Lack of Future Support: The Runnable interface does not integrate directly with Java's Future API, which allows asynchronous computation and retrieval of results from concurrent tasks. This makes it cumbersome to manage the execution status and results of Runnable tasks.
  • Difficulty in Task Abstraction: Runnable tasks are tightly coupled with the run() method, which limits the level of abstraction that can be achieved when defining concurrent tasks. This can make it challenging to reuse and compose Runnable-based tasks in complex applications.
     

Read more about Object-Oriented Programming

Frequently Asked Questions

What is Java Callable interface?

The Callable interface is a functional interface in Java. It is a type of interface that has a return type.

How do you implement the Callable interface in Java?

You have to create a class that implements the callable interface in Java before you can use it. This class also provides an implementation for the run() method. 

What is the difference between Callable interface and runnable interface in Java?

Callable and Runnable are interfaces in Java for defining tasks that can be executed asynchronously. Callable can return results or throw exceptions, whereas Runnable cannot. Future is a container for the result of an asynchronous task, allowing you to retrieve the result when it's ready or handle exceptions.

When should we use Callable Java?

Use Callable in Java when you need to execute tasks that return results or throw exceptions in multithreaded environments, offering better control and error handling.

What is the difference between Callable and future in Java?

Callable defines tasks, while Future represents the result of asynchronous computation. Callable is a functional interface, while Future is an interface for managing asynchronous computation results and completion status.

Conclusion

This article discusses the topic of the callable interface in Java in detail. We have seen the callable interface's definition, syntax, and features in Java. Along with this, we saw the example code with output and a proper explanation.

We hope this blog has helped you enhance your knowledge of the callable interface in Java. If you want to learn more, then check out our articles.

To learn more about Data Structures and Algorithms, you can enroll in our course on DSA in Java.

Previous article
Interfaces
Next article
Marker Interface in Java
Live masterclass