Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The Callable and Runnable interfaces in Java are both used to represent tasks that can be executed by another thread.
An interface is an abstract class in Java that includes related methods. It is similar to a class, but unlike a class, the methods are not instantiated here. Instead, other classes implement the interface and provide the necessary functionality.
There are two interfaces in Java to execute a task asynchronously, Runnable and Callable. In other words, They are used to encapsulate functions that are supposed to be completed by another thread. These are widely used in multithreaded programming to perform tasks concurrently.
Runnable is an interface in Java. It defines a single method run( ). It describes a task that can be executed in a separate thread. It does not return any result, but it can perform some actions. It cannot throw a checked exception. The run( ) method must be overridden to define the thread's task.
Once the run( ) method is defined, we can pass the Runnable instance to a Thread constructor or ExecutorService and start the thread using the start() method. To know more about threads, visit this blog.
Example Code
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
You can also try this code with Online Java Compiler
In the above example, the MyRunnable class implements the Runnable interface and overrides the run( ) method to print a message. The main( ) method creates a MyRunnable instance and a Thread instance, passing the MyRunnable instance to the Thread constructor. The start( ) method of the Thread instance is called to start the thread, which executes the run( ) method of the MyRunnable instance.
The above class can also be executed using ExecutorService. To read more about the runnable interface, visit this blog.
Output
What is Callable Interface?
Callable is an interface in Java. It defines a single method call( ). It is also similar to a runnable interface, but it is used when a task returns a result. It can throw a checked exception. The call( ) method must be overridden to define the thread's task.
Once the call( ) method is defined, we can pass the Callable instance to an ExecutorService and submit it using the submit( ) method. The submit( ) method returns a Future object, which signifies the result of the task and can be used to retrieve the result or cancel the task.
Example Code
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
int result = future.get();
System.out.println("Result = " + result);
executor.shutdown();
}
}
You can also try this code with Online Java Compiler
In the above example, the MyCallable class implements the Callable<Integer> interface and overrides the call( ) method to calculate the sum of numbers from 1 to 5. The main( ) method creates an executor service using the Executors.newSingleThreadExecutor( ) method, which creates a thread pool with a single thread.
It then submits the MyCallable instance to the executor service using the submit( ) method, which returns a Future object representing the result of the task. The get( ) method of the Future object is called to retrieve the result, which is printed to the console. Finally, the executor service is shut down using the shutdown( ) method.
Output
Difference Between Callable and Runnable in Java
Let’s see some differences between callable and runnable interfaces:
Parameter
Runnable Interface
Callable Interface
Generics
Runnable is not a generic interface.
Callable allows us to specify the type of result that will be returned by the call() method.
Return value
The runnable interface has a run( ) method that does not return anything.
The Callable interface has a call( ) method that returns a value.
Future object
Runnable does not provide this functionality.
When a Callable is submitted to an ExecutorService, it returns a Future object that can be used to retrieve the result of the computation.
Exception handling
The run( ) method of the Runnable interface cannot throw a checked exception.
The call( ) method of the Callable interface can throw an exception.
Package
It is a part of java.lang package.
It is a part of java.util.concurrent package.
Checked Exceptions
Exceptions are events that occur during the execution of a program and disturb the normal flow of the program. The exceptions have a Throwable type class. When an error happens in a method, the method creates an object (or any subtype of Throwable) and passes it to the runtime system. This object is called the exception object.
In Java, there are two exceptions, Checked and Unchecked. The Java compiler checks checked exceptions, which are also called compile-time exceptions. They are expected to occur under certain circumstances and can be handled by the method's caller. For example, if a method accesses a SQL database, it may throw a checked SQLException if the database is not present at the provided URL endpoint. The method’s caller can catch the exception and take appropriate action, like notifying the user about the error or logging the error.
Can a Callable be parameterized with a type for its return value?
Callable is a generic interface that takes a type parameter for its return value. For example, Callable<Integer> represents a Callable that returns an Integer.
What is the main difference between Callable and Runnable in Java?
The main difference between Callable and Runnable in Java is that Callable can return a value while Runnable cannot.
Can Callable and Runnable both throw exceptions?
Yes, both Callable and Runnable can throw exceptions. However, Callable's call( ) method can throw checked exceptions, while Runnable's run( ) method is not.
Which interface should be used if a computation needs to return a value?
A Callable interface should be used if a computation needs to return a value.
Can a class implement both Callable and Runnable interfaces?
Yes, a class can implement both Callable and Runnable interfaces. However, they serve different purposes and should be used based on the specific requirements of the task.
Conclusion
In this article, we briefly discussed different interfaces in Java and the difference between callable and runnable. The main differences between Callable and Runnable in Java are related to the return value, exception handling, future object, and generics. If we need to return a value or handle checked exceptions, we should use Callable. If we need to check the status of a task or do not need a return value, Runnable would be the better choice.