Java: Callable and Future - Multi-threading

Public on October 29, 2015

The Callable interface declares public T call() throws Exception. Now we can return a result, have it strongly typed as declared in our implementation and even throw Exceptions. While there are some utility methods in the Executors class to convert your Runnable instances as discussed in Part 3, you would do well to review your current implementations ofRunnable or subclasses of Thread. Why bother? Primarily to double check and remove the workaround you may have implemented to address the lack of support for thrown Exceptions. At the same time, you may wish to make use of the ability to return results right in the execution method eliminating any need to cast to retrieve values.

Here’s where the combined power of the thread pools and Callable come together. Future is another new interface introduced in 1.5. When you submit a Callable to one of the thread pools, you are provided an instance of Future that is typed to the Callable you passed in. This object substitutes for an actual Thread instance that you would have used prior to 1.5. Whereas you previously had to do Thread.join() or Thread.join(long millis), now you may use them as in this example.
Code Example : 
 import java.lang.reflect.Array;  
 import java.text.SimpleDateFormat;  
 import java.util.ArrayList;  
 import java.util.Calendar;  
 import java.util.concurrent.Callable;  
 import java.util.concurrent.ExecutionException;  
 import java.util.concurrent.Executor;  
 import java.util.concurrent.ExecutorService;  
 import java.util.concurrent.Executors;  
 import java.util.concurrent.Future;  
 public class CallableFuture {  
      public static void main(String[] args) {  
           ExecutorService pool = Executors.newCachedThreadPool();  
           Future<ArrayList<String>> test = pool.submit(new Callable<ArrayList<String>>() {  
                public ArrayList<String> call() throws Exception {  
                     // TODO Auto-generated method stub  
                     ArrayList<String> arrFuture = new ArrayList<>();  
                     for(int i = 0 ; i < 10; i++){  
                          String timeStamp = new SimpleDateFormat("yyyy-MM-dd : HH-mm-ss").format(Calendar.getInstance().getTime());  
                          arrFuture.add(i+ " : "+timeStamp);  
                     return arrFuture;  
           try {  
                ArrayList<String> arr = test.get();  
                for(int i = 0 ; i < arr.size();i++){  
           } catch (InterruptedException | ExecutionException e) {  
                // TODO Auto-generated catch block  

[Advertising]Faster Thinking - Speed up your brain

Faster Thinking Game

sentiment_satisfied Emoticon