Codementor Events

Runnable vs Callable

Published Oct 03, 2020Last updated Sep 28, 2021
Runnable vs Callable

In this article you will learn what is a runnable , what is a callable and the difference between the two in java, runnable vs callable. These concepts are important when you are dealing with concurrency.

Concurrency basically means there is not just one execution thread in your program, but several executions or threads, potentially happening simultaneously. Therefore different pieces of the code might be executed at the same time.

Runnable

The Runnable interface in java enables you to define a block of code that can be executed within its own thread. Therefore if you create several runnable classes and execute them, and you will have several threads running at the same time within the same process or program. This is known as concurrency.

See examples of how to use a runnable interface

Callable

Next is callable. Callable is also a java interface and as Runnable, you can use it to run tasks in parallel. However there is a key difference. The callable can return the result of the task or throw an exception. The Callable interface is included in Java to address some of runnable limitations.

See examples of how to use a runnable interface

Runnable vs Callable - The difference

The main difference between Runnable and Callable is that Callable will return the result of executing the task to the caller. If you use Runnable you can't return anything, any result will need to be saved in separated shared structure or database. To understand this difference runnable vs callable, you can compare the two interfaces.

public interface Runnable {
    public abstract void run();
}

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

How to execute a runnable
How to execute a callable

I hope you enjoy the article and thank you so much for reading and supporting this blog! 🙂

Discover and read more posts from Marta Rey
get started