Tuesday, December 2, 2014

The difference between the Runnable and Callable interfaces in Java..

  • A Callable needs to implement call() method while a Runnable needs to implement run() method.
  • A Callable can return a value but a Runnable cannot.
  • A Callable can throw checked exception but a Runnable cannot.
  • A Callable can be used with ExecutorService#invokeXXX methods but a Runnable cannot be.
    public interface Runnable {
        void run();
    }
    
    public interface Callable<V> {
        V call() throws Exception;
    }
     
    NOTE : Inside your class you can make the calls to Callable and Runnable
     on a single thread executor, making this mechanism similar to a serial 
    dispatch queue. So as long as the caller calls your Runnable wrapped 
    methods the calling thread will execute really fast without blocking. As
     soon as it calls a Callable wrapped in Future method it will have to 
    block till all the other queued items are executed. Only then the method
     will return with values. This is a synchronization mechanism. 

No comments:

Post a Comment