What Callable and Runnable Interfaces in java

public interface Callable<V> {
     * Computes a result, or throws an exception if unable to do so.
     * @return computed result
     * @throws Exception if unable to compute a result
    V call() throws Exception;

The call() method is called in order to execute the asynchronous task. The call() method can return a result. If the task is executed asynchronously, the result is typically propagated back to the creator of the task via a  Java Future. This is the case when a Callable is submitted to an ExecutorService for concurrent execution.

The call() method can also thrown an Exception in case the task fails during execution.

Java  Feature 


A Java Futurejava.util.concurrent.Future, represents the result of an asynchronous computation. When the asynchronous task is created, a Java Future object is returned. This Future object functions as a handle to the result of the asynchronous task. Once the asynchronous task completes, the result can be accessed via the Future object returned when the task was started.

public interface Future<V> {

    boolean cancel(boolean mayInterruptIfRunning)

    V       get();

    V       get(long timeout, TimeUnit unit);

    boolean isCancelled();

    boolean isDone();


Runnable on the other hand is interface that declares run() method that is called when you create a Thread with the runnable and call start() on it. You can also directly call run() but that just executes the run() method is same thread.
public interface Runnable {
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     * @see     java.lang.Thread#run()
    public abstract void run();

We can   differentiate   these  as   below table  


Runnable cannot be parameterized .

Runnable has run() method .  
Runnable.run() returns void  .      

Can not throw Checked Exceptions   .

Callable is a parameterised  type whose type parameter indicates the return type of its run method |

Callable has call()  method                                                                      

Callable.call() returns a value of Type T   

Can throw Checked Exceptions                                                                                                                         

What Callable and Runnable Interfaces in java What    Callable   and   Runnable    Interfaces  in java Reviewed by Mukesh Jha on 12:05 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.