The Callable
and Supplier
functional interfaces in java.util.concurrent
and java.util.function
packages respectively have the following signature-
public interface Callable<V> {
V call() throws Exception;
}
public interface Supplier<T> {
T get();
}
Are there some specific use case where each one of them fit more than the other?
The Supplier Interface is a part of the java. util. function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a value of type T.
Interface Callable<V> This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call .
A supplier is any method which takes no arguments and returns a value. Its job is to supply an instance of an expected class. Whereas, a consumer is a method that consumes some value (as in method argument), and does some operations on them. So a Consumer is any method which takes arguments and returns nothing.
Their difference in usage can be seen from their respective documentation:
Callable
:
A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread.
Supplier
:
Represents a supplier of results.
There is no requirement that a new or distinct result be returned each time the supplier is invoked.
This means that the caller of Callable.call
expects an exception to be thrown and will handle the exception accordingly. This is useful for tasks like reading and writing to files, where many kinds of IOException
s can be thrown. Callable
is also designed to be run on another thread.
Supplier
on the other hand, is very general. It just "supplies a value" and that's it.
So Callable
is more specialised than Supplier
. If you are not dealing with another thread or your task is very unlikely to throw an exception, Supplier
is recommended.
Apart from the obvious, Callable throwing an exception, the difference is semantic. They have different names because they represent different things. The purpose is to make code easier to understand. When you use a Callable, your interface choice implies that the object is going to be executed by another thread. When you use Supplier you imply that it's just an object that supplies data to another component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With