One of the features that we can use with Threadpools is the submit()
method which allow us to know when the thread as finish his work. We can do this thanks to the Future
object, which return us an object from the Callable that we can use to our own objetives.
Here is an example about how to use the Callable instance:
public class CallablesExample{
//Create MyCustomCallable instance
List<Future<String>> mFutureList = new ArrayList<Future<String>>();
//Create a list to save the Futures from the Callable
Callable<String> mCallable = new MyCustomCallable();
public void main(String args[]){
//Get ExecutorService from Executors utility class, Creating a 5 threads pool.
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 100; i++) {
//submit Callable tasks to be executed by thread pool
Future<String> future = executor.submit(mCallable);
//add Future to the list, we can get return value using Future
mFutureList.add(future);
}
for (Future<String> fut : mFutureList) {
try {
//Print the return value of Future, Notice the output delay in console
//because Future.get() stop the thread till the task have been completed
System.out.println(new Date() + "::" + fut.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
//Shut down the service
executor.shutdown();
}
class MyCustomCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
//return the thread name executing this callable task
return Thread.currentThread().getName();
}
}
}
As you can see, we create a Threadpool with 5 Threads, this means that we can throw 5 callables parallel. When the threads finish, we will get and Future object from the callable, in this case the name of the thread.
WARNING
In this example, we just use the Futures as a object inside the array to know how many threads we are executing and print that many times a log in console with the data that we want. But, if we want to use the method Future.get()
, to return us the data that we saved before in the callable, we will block the thread till the task is completed. Be care with this kind of calls when you want perform this as fast as possible