Monday, January 17, 2011

Part 1: java.util.concurrent - Runnable Vs Callable in Java

About Runnable:
Runnable interface is implemented by the Thread class as well and it's a common protocol for all the objects who wish to execute in a different thread. It's one of the ways of creating threads in Java. The other way to create a thread is by subclassing the Thread class. A class implementing Runnable interface can simply pass itself to create a Thread instance and can run thereafter. This eliminates the need of subclassing the Thread class for the purpose of executing the code in a separate thread.
As long as we don't wish to override other methods of the Thread class, it may be a better idea to implement the Runnable interface to enable multithreading capabilities to a class than enabling the same by extending the Thread class.

About Callable:
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 interface which has been a part of Java since Java 1.0.

Similarities:
1) Both threads can be used to cause a separate stack for a thread.

2) Both has only one method : Inside Runnable it is called as
public abstract void run( );
Inside callable the method is being called as
public abstract call() ;
(Note : V can be any valid object in JAVA)

Differences:

1) Return Type -
public abstract void run() --> Return type "void"
public abstract call() --> Return type "Any valid JAVA Object"

2) Run method can not throw any checked Exception, whereas
public abstract call() throw checkedException
Call method can throw any checked Exception.

Note: You can also >> DOWNLOAD << the program from here.
Copyright (c) 2011 http://www.jovialjava.blogspot.com


4 comments:

Javin @ thread interview questions said...

Good article, Thanks. I have also shared differences between Runnable and Thread in Java let me know how do you find it.

Gaku said...

It seems to me that CallableTask runs on the main thread. It is wrapped with FutureTask, but callTask.run() is just executed on the main thread.

I guess it also needs something like:

Thread runCallable = new Thread(call);
runCallable.start();

Shri said...
This comment has been removed by the author.
Shri said...

if you want to run the the callable in a thread then the above code should be modified a follows

instead of

callTask.run();

it should be

Thread callTaskThread = new Thread(callTask);
callTaskThread.start();