java.util.concurrent.Callable way of creating threads

gudii9
gudii9 used Ask the Experts™
on
Hi,

To create thread i am only familiar with 2 ways.
1. extending Thread class
2. implementing Runnable interface.

I am not familiar with below third method
java.util.concurrent.Callable way of creating threads

When this 3rd way is introduced and what are advantaged and disadvantages of using it over other two ways. please advise
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
CPColinSenior Java Architect
Commented:
According to the Javadocs, the Callable interface was introduced in Java 1.5. See ExecutorService.submit(Callable) for more information on how you'd use it. In Java 8, you could even do something like this:

ExecutorService executorService = ExecutorService.newCachedThreadPool();
Future<SomeClass> future = executorService.submit(SomeClass::computeValue);

Open in new window


This code will execute that computeValue() method on a separate thread and return the result in that Future object.

As for which style you should use, it really just depends on what you're doing and how you want to do it. If you're doing something that's really simple, you might as well implement Runnable and skip the extra complexity of using ExecutorService.
The main reason to use Callable is when you want to get something back from the thread.

In other words the difference between it and Runnable is that Runnable doesn't return a value - it's method (run) return void.  Callable's method (call) returns an Object.

Also Callable's call method is allowed to thrown an exception, so you can also retrieve exceptions from threads, which otherwise is not so easy.

Aside from that it's just like using Runnable.

And FYI, these days you should never be extending Thread.  That's very much old school and the Executor framework makes it totally unnecessary.

Doug

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial