views:

1991

answers:

4

What is the difference between using the Runnable and Callable interfaces when designing a concurrent thread in Java, why would you choose one over the other?

+16  A: 

See explanation here.

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

smink
+3  A: 

I found this in another blog that can explain it a little bit more these differences:

Though both the interfaces are implemented by the classes who wish to execute in a different thread of execution, but there are few differences between the two interface which are:

  • A Callable instance returns a result of type V, whereas a Runnable instance doesn't
  • A Callable instance may throw checked exceptions, whereas a Runnable instance can't

The designers of Java felt a need of extending the capabilities of the Runnable interface, but they didn't want to affect the uses of the Runnable interface and probably that was the reason why they went for having a separate interface named Callable in Java 1.5 than changing the already existing Runnable

amoran
A: 

What are the differences in the applications of Runnable and Callable. Is the difference only with the return parameter present in callable.

See the answers to this question.

Can you please provide a simple example which demonstrates the typical use of both.

Use your imagination :-).

What is the need of having both if Callable can do all that Runnable does.

Runnable has been around since Java 1.0, but Callable was only introduced in Java 1.5 ... to handle use-cases that Runnable does not support. In theory, the Java team could have changed Runnable.run() method, but this would have broken binary compatiblity with pre-1.5 code, requiring recoding to migrating old Java code to the latest JVMs. That is a BIG NO-NO as far as the Java team is concerned.

Stephen C
A: 

As it was already mentioned here Callable is relatively new interface and it was introduced as a part of concurrency package. Both Callable and Runnable can be used with executors. Class Thread (that implements Runnable itself) supports Runnable only.

You can still use Runnable with executors. The advantage of Callable that you can send it to executor and immediately get back Future result that will be updated when the execution is finished. The same may be implemented with Runnable, but in this case you have to manage the results yourself. For example you can create results queue that will hold all results. Other thread can wait on this queue and deal with results that arrive.

AlexR