Shall Callable be preferred over Runnable?

后端 未结 5 1741
小蘑菇
小蘑菇 2021-02-01 02:04

I have understood the difference between Runnable and Callable interface in Java. From Java 1.5 additional features has been added to Runnable

5条回答
  •  萌比男神i
    2021-02-01 02:51

    IMHO, Runnable is a better type to use when taking as argument a function which

    • doesn't have a returned value, but only side effects
    • must handle exceptions, and not propagate them

    Don't forget that Callable.call() throws Exception. That means that if you take a Callable as argument, this Callable can throw any kind of exception, and you must have a way to handle them all in a correct way. If you can't do that, it's better to let the implementor of the Callable handle the exception as he wants to, and make the argument a Runnable to make that clear.

提交回复
热议问题