Callable vs Supplier interface in java

前端 未结 3 1382
春和景丽
春和景丽 2021-02-19 16:35

The Callable and Supplier functional interfaces in java.util.concurrent and java.util.function packages respectively have the

3条回答
  •  北海茫月
    2021-02-19 17:38

    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 IOExceptions 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.

提交回复
热议问题