Over a million developers have joined DZone.

Callable vs Runnable - the Brawl of the Runners

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

Runnable : I am the Yoda of multithreading. For generations, I was the only way (other than lang.Thread) that people could do parallel activities in Java. Remember the cool method that I have - run. Too bad, it returns a void though.

Callable : I am a Runnable, just better and cooler. I have this amazing method called call which returns the result of my work. The return type of call is a cool generic and the result could be got using Future. Now, top that Runnable !!

Runnable : Yeah, Yeah, Whatever. Probably, you just came into existence to fill the gaps left in my design. Like, you know, my run method does not throw any Exception which would just mean that if the task wants to throw an exception, it can throw only a Runtime exception.

Callable : I agree. I do stand on your shoulders. And it’s no wonder the call method throws an Exception which enables the task to throw a checked exception back to the caller.

Runnable API

void    run() 

Callable API

  V     call() throws Exception

More details on the Future is here

Unity in Diversity

FutureTask is an interesting class which can accept both Runnable and Callable in its constructor. Since FutureTask implements Runnable, it can safely pass by the Executor.execute door. Remember, the Executor.execute accepts only a Runnable. I still need to figure out why somebody would want that considering the execute method has a void return type and cannot return results

Shamelessly copied and modified from javadoc

Executor executor= …

FutureTask<String> future =

   new FutureTask<String>(new Callable<String>() {
     public String call() {
       … do your thing…




Further reading :

Alex Miller’s amazing blog

Alex Miller’s concurrency gotchas

Vogella’s article on comparison with original API

Good introduction to concurrency in general

Highly recommended book on Java concurrency

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.


Published at DZone with permission of Arun Manivannan , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}