Wednesday, January 19, 2011

Part 2: java.util.concurrent - Future <T>

Future<T>:
A Future represents the result of an asynchronous computation. Future has been provide with some really powerful methods. For Instance -
1) We can check whether a task has been completed or not.
2) We can cancel a task.
3) Check whether task was cancelled or complete normally.


Methods-


boolean cancel(boolean mayInterruptIfRunning)
This method does following -
1) If the process(Thread) has not started, then cancel the thread.
2) If the process has started, then check if 
mayInterruptIfRunning = true ==> Inturrept the thread and cancel it
mayInterruptIfRunning = false ==> Let it run
This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason.
After this method returns, subsequent calls to isDone() will always return true.
Subsequent calls to isCancelled() will always return true if this method returned true.


boolean isCancelled()
    Returns true if this task was cancelled before it completed normally


V get() throws InterruptedException, ExecutionException
This method is a blocking call. It will cause JVM to wait if necessary for the computation to complete, and then retrieves its result.


boolean isDone()
    Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation - in all of these cases, this method will return true.
Please >>download<< the program from here.
/**
*Copyright (C) 2010  Jovial Java Admin [email: jovialjava.blogspot@gmail.com]
*
*This program is free software: you can redistribute it and/or modify
*it under the terms of the GNU General Public License as published by
*the Free Software Foundation, version 3 of the License.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program.  If not, see .
*@date Jan 19, 2011
*@author JovialJava
*/
package com.jovialjava.blog.threads;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureExample {
 /**
  * Executor pool is a new concept in JAVA 5+, it can help to release 
  * a thread. It maintains a pool of threads, It reuses them, also align them in 
  * a queue. Here we are creating pool of 1 thread.
  */
 private static final ExecutorService executorPool=Executors.newFixedThreadPool(5);
 
 public static void main(String... args){
  CallableTask call = new CallableTask();  
  try{
   /**
    * Future is result of asynchronous computation.
    * It may possible that CallableTask has not started yet
    * but 'ExecutorService' gives the result via Future
    * Object.
    */
   Future future = executorPool.submit(call);
   /**
    * We can check if CallableTask has been completed.
    */
   System.out.println("Status of Callable Task [Is Completed ? "+ future.isDone()+ "]");
   /**
    * We can get the result of callable Task.
    * Note : future.get() is a blocking call, It will wait until the associated process finishes.
    */
   System.out.println("Result of callable task ["+ future.get()+"]");
   /**
    * We can cancel the task.
    */
   System.out.println("Trying to cancel the task [Is Cancelled ? "+ future.cancel(false)+ "]");
   /**
    * We can see if the task was canceled.
    * Returns true if this task was canceled before it completed normally
    */
   System.out.println("Was task canceled before normal complition ? -"+ future.isCancelled());
   
   
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   executorPool.shutdownNow();
  }
  
 }

 
 /*
  *Callable is defined as Callable
  *
  */
 public static class CallableTask implements Callable{
    
  public String call( ){
   System.out.println("Inside CALLABLE TASK");
   return "~~JOVIAL JAVA~~";
  }
 } 
}

2 comments:

Sanjeev said...

awesome post. made the understanding clear without effort.

Sanjeev said...

awesome post. made the understanding clear.