Callable & Runnable used for achieving concurrency in the programming thread.
Java introduced Callable from Java 1.5 in java.util, and Runnable is from 1.0 in java.lang. Callable achieves what Runnable cannot achieve, like verifying the execution status once it is submitted for execution.
Here are few difference and advantage over Runnable interface in Java.
Runnableobject does not return a result whereas a
Callableobject returns a result.
Runnableobject cannot throw a checked exception wheras a
Callableobject can throw an exception.
Few similarities include
- Instances of the classes that implement Runnable or Callable interfaces are potentially executed by another thread.
- Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.
- Both are functional interfaces and can be used in Lambda expressions since Java8.
Snippet for execution of Runnable object via Executors:
Runnable worker = new RunnableObject("threadName"); threadExecutor.execute(worker);
Snippet for execution of Callable object via Executors:
Callable worker = new CallableObject("threadName"); Future future = callableExecutor.submit(worker);
submit is used for invoking callable object and returns future object, Future is used to store a result or status obtained from a different thread, where as runnable doesn’t have capability to return any such kind of essence.