Saturday 8 March 2014

Future: get() : get result of task

V get() throws InterruptedException, ExecutionException
function returns the result from the given task. If the task still computing the result, then this method waits until the task finishes. Once the task finishes it gets the result. Get() throws InterruptedException if the current thread was interrupted while waiting and throws ExecutionException if the computation threw an exception.

Example
CallableTask.java
import java.util.concurrent.*;
import java.util.*;

public class CallableTask implements Callable{
    String name;
    CallableTask(String name){
        this.name = name;
    }
    
    public String call(){
        try{
            System.out.println(name +" Started Executing");
            Thread.sleep(1000);
            System.out.println(name +" Finishes Execution");
        }
        catch(Exception e){
            
        }
        return (new Date() + " :: " + name);
    }
}

SimpleThreadPool.java
import java.util.concurrent.*;
import java.util.*;

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
   CallableTask tasks[] =new CallableTask[5];
   for(int i=0; i<5; i++){
    tasks[i] = new CallableTask("task" + i);
    Future<String> future = exec.submit(tasks[i]);
                                System.out.println(future.get());
   }
                        exec.shutdown();
                        System.out.println("Execution Completed");
 }
}

Output
task0 Started Executing
task0 Finishes Execution
Sat Mar 08 11:38:52 IST 2014 :: task0
task1 Started Executing
task1 Finishes Execution
Sat Mar 08 11:38:53 IST 2014 :: task1
task2 Started Executing
task2 Finishes Execution
Sat Mar 08 11:38:54 IST 2014 :: task2
task3 Started Executing
task3 Finishes Execution
Sat Mar 08 11:38:55 IST 2014 :: task3
task4 Started Executing
task4 Finishes Execution
Sat Mar 08 11:38:56 IST 2014 :: task4
Execution Completed

Try to run the program, and you observe that get() waits for the result. So it blocks the current thread execution until the computation finishes.

ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
Statement creates a thread pool of 3 threads.

exec.submit(tasks[i])
Submit the tasks to the thread pool. When the task is submitted, ThreadPool assigns a thread to execute the call method of the Callable Object.


Future Interface                                                 Future: Wait for the result for some time                                                 Home

No comments:

Post a Comment