Search code examples
javajava.util.concurrent

Understanding the code execution path for given code


I am new to Java, Can anyone explain me which method invokes the call method in below given code , also help me to understand the code execution path for give code:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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 MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);         
        return Thread.currentThread().getName();
    }

    public static void main(String args[]){
        //Get ExecutorService from Executors utility class, thread pool size is 10
        ExecutorService executor = Executors.newFixedThreadPool(10);            
        List<Future<String>> list = new ArrayList<Future<String>>();            
        Callable<String> callable = new MyCallable();

        for(int i=0; i< 100; i++){              
            Future<String> future = executor.submit(callable);              
            list.add(future);
        }

        for(Future<String> fut : list){
            try {               
                System.out.println(new Date()+ "::"+fut.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }           
        executor.shutdown();
    }
}

Solution

  • The code submits a Callable 100 times to an ExecutorService containing 10 threads and captures the Futures that indicate when each Callable has been run.

    ExecutorService executor = Executors.newFixedThreadPool(10);            
    List<Future<String>> list = new ArrayList<Future<String>>();            
    Callable<String> callable = new MyCallable();
    
    for (int i = 0; i < 100; i++)
    {              
      Future<String> future = executor.submit(callable);              
      list.add(future);
    }
    

    Once each of the 10 threads are running a Callable the remaining Callables will be queued up and are run as each thread becomes available.

    After all the Callables have been added, the next block of code gets the result from each Future, the important thing being that the calling thread will block on the call to Future.get until the Callable finishes, so the results will be printed in the order the Callables were added.

    for(Future<String> fut : list)
    {
      try 
      {               
        System.out.println(new Date() + "::" + fut.get());
      } 
      catch (InterruptedException | ExecutionException e) 
      {
        e.printStackTrace();
      }
    }     
    

    Finally the executor is shutdown to kill the threads it contains.

    executor.shutdown();