Can I use Callable threads without ExecutorService?
In the case of runnable job Thread won’t return anything after completing the job.
If a thread is required to return some result after execution then we should go for callable.
Callable interface contains only one method call()
public Object call() throws Exception.
If we submit a callable object to executor then after completing the job thread returns an Object of type Future i.e Future object can be used to retrieve the result from callable job.
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class CallableDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { MyCallable[] jobArray = { new MyCallable(10),new MyCallable(20),new MyCallable(30),new MyCallable(40),new MyCallable(50)}; ExecutorService service = Executors.newFixedThreadPool(3); for(MyCallable job : jobArray) { Future f = service.submit(job); System.out.println(f.get()); } service.shutdown(); } } class MyCallable implements Callable{ int number; MyCallable(int number){ this.number = number; } public Object call() throws Exception { System.out.println("Thread execution started for "+number+" Thread Name : "+Thread.currentThread().getName()); int total=0; for(int i=0;i<=number;i++) { total = total + i; } return total; } }
Difference between Runnable and Callable
Runnable | Callable |
1. If a thread is not required to return anything after completing the job then we should use Runnable | 1. If a thread is required to return something after completing the job then we should go for callable. |
2. Runnable interface contains only one method run() | 2. Callable interface contains only one method call() |
3. Runnable job not required to return anything and hence return type of run method is void | 3. Callable job is required to return something and hence return type of call method is object. |
4. Within the run method if there is any chance of raising checked exception we need to handle it with try catch because we can’t use throws keyword in run method | 4.With in call method if there is any chance of raising checked exception we are not required to handle it using try catch because call method already throws exception. |
5. Runnable interface present in java.lang package | 5. Callable interface present in java.util.concurrent package |
6. Introduced in java 1.0 version | 6. Introduced in java 1.5 version |