Saturday, September 6, 2014

13. Callable and Future

Java Multithreading: Callable and Future
How to use Callable and Future in Java to get results from your threads and to allow your threads to throw exceptions. Plus, Future allows you to control your threads, checking to see if they’re running or not, waiting for results and even interrupting them or descheduling them.

Code For This Tutorial
import java.io.IOException;
import java.util.Random;
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; 


public class App {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        
        Future<Integer> future = executor.submit(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                Random random = new Random();
                int duration = random.nextInt(4000);
                 System.out.println(duration);
                if(duration > 2000) {
                    throw new IOException("Sleeping for too long.");
                }
                
                System.out.println("Starting ...");
                
                try {
                    Thread.sleep(duration);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                System.out.println("Finished.");
                
                return duration;
            }
            
        });
        
        executor.shutdown();
        
        try {
            System.out.println("Result is: " + future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            IOException ex = (IOException) e.getCause();
            
            System.out.println(ex.getMessage());
        }
    }


}

Output:
Starting ...
Finished.
Result is: 792

1 comment:

  1. Happy to found this blog. Good Post!. It was so good to read and useful to improve my knowledge as updated one, keep blogging. Hibernate Training in Electronic City
    Java Training in Electronic City

    ReplyDelete