Callable vs Runnable - the Brawl of the Runners
Join the DZone community and get the full member experience.
Join For FreeRunnable : 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.
void run()
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… }}); executor.execute(future);
Further reading :
Alex Miller’s concurrency gotchas
Vogella’s article on comparison with original API
Published at DZone with permission of Arun Manivannan, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments