Showing posts with label Future interface. Show all posts
Showing posts with label Future interface. Show all posts

Saturday, 8 March 2014

isCancelled(): Cancellation status

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

Example
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){
   System.out.println("Task Interrupted " + e);
  }
  return (new Date() + " :: " + name);
 }
}
   
import java.util.concurrent.*;
import java.util.*;

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  List<Future<String>> l1 = new ArrayList<Future<String>> ();
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  CallableTask task1 = new CallableTask("task1");

  Future<String> f1 = exec.submit(task1);
  Future<String> f2 = exec.submit(task1);

  f1.cancel(false);
  f2.cancel(true);

  System.out.println("is the task cancelled " + f1.isCancelled());
  System.out.println("is the task cancelled " + f2.isCancelled());
  exec.shutdown();
 }
}

Output
task1 Started Executing
task1 Started Executing
is the task cancelled true
is the task cancelled true
Task Interrupted java.lang.InterruptedException: sleep interrupted
task1 Finishes Execution

As you observe the output, task1 finishes execution normally, where as task2 thrown InterruptedException. Since f1 calls cancel with false as argument and f2 calls cancel with true as an argument.

f1.cancel(false)
f2.cancel(true)

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

exec.submit(tasks)
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.


Check completion status of the task                                                 ExecutorService interface                                                 Home

IsDone() : Check completion status of task

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.

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");
   System.out.println(name +" Finishes Execution");
  }
  catch(Exception e){
   System.out.println("Task Interrupted " + e);
  }
  return (new Date() + " :: " + name);
 }
}

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

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  List<Future<String>> l1 = new ArrayList<Future<String>> ();
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

  CallableTask task1 = new CallableTask("task1");
  Future<String> f1 = exec.submit(task1);
  Thread.sleep(1000);
  System.out.println("is the task finished " + f1.isDone());
  exec.shutdown();
 }
}
  
Output
task1 Started Executing
task1 Finishes Execution
is the task finished true
  
ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
Statement creates a thread pool of 3 threads.

exec.submit(tasks)
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.   




Cancel task exection                                                 Cancellation status of the task                                                 Home

Future : cancel task execution

Future interface provides a method to cancel the task.

boolean cancel(boolean flag)
Method attempts to cancel the task. If the task already completed then this attempt will fail. If the flag is true then the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete

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){
            System.out.println("Task Interrupted " + e);
        }
        return (new Date() + " :: " + name);
    }
}

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

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  
                List<Future<String>> l1 = new ArrayList<Future<String>> ();
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
   
               CallableTask task1 = new CallableTask("task1");
               
               Future<String> f1 = exec.submit(task1);
                Thread.sleep(100);
               System.out.println("cancel method returned " + f1.cancel(true));
              
               exec.shutdown();
 }
}

Output
task1 Started Executing
cancel method returned true
Task Interrupted java.lang.InterruptedException: sleep interrupted

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

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  
                List<Future<String>> l1 = new ArrayList<Future<String>> ();
  ExecutorService exec = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
   
               CallableTask task1 = new CallableTask("task1");
               
               Future<String> f1 = exec.submit(task1);
                Thread.sleep(100);
               System.out.println("cancel method returned " + f1.cancel(false));
              
               exec.shutdown();
 }
}

Output
task1 Started Executing
cancel method returned true
task1 Finishes Execution

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.

Some Points to remember
1. If the cancel method unable to cancel the task, then the cancel method returns false.

Get the result of the task                                                 Check the completion status of task                                                 Home

Future : get(long timeout, TimeUnit unit) : get the result of task

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

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);
    }
}

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

class SimpleThreadPool{
 public static void main(String args[])throws Exception{
  
                List<Future<String>> l1 = new ArrayList<Future<String>> ();
  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]);
                                l1.add(future);
                                try{
                                    System.out.println(future.get(100,TimeUnit.MILLISECONDS));
                                }
                                catch(TimeoutException e){
                                       System.out.println(e); 
                                        }
   }
                        exec.shutdown();
                        exec.awaitTermination(5, TimeUnit.SECONDS);
                        System.out.println("Results of the tasks are");
                        for(Future f1 : l1){
                            System.out.println(f1.get());
                        }
                        System.out.println("Execution Completed");
 }
}

Output
task0 Started Executing
java.util.concurrent.TimeoutException
task1 Started Executing
java.util.concurrent.TimeoutException
task2 Started Executing
java.util.concurrent.TimeoutException
java.util.concurrent.TimeoutException
java.util.concurrent.TimeoutException
task0 Finishes Execution
task3 Started Executing
task1 Finishes Execution
task4 Started Executing
task2 Finishes Execution
task3 Finishes Execution
task4 Finishes Execution
Results of the tasks are
Sat Mar 08 11:45:45 IST 2014 :: task0
Sat Mar 08 11:45:45 IST 2014 :: task1
Sat Mar 08 11:45:45 IST 2014 :: task2
Sat Mar 08 11:45:46 IST 2014 :: task3
Sat Mar 08 11:45:46 IST 2014 :: task4
Execution Completed


future.get(100,TimeUnit.MILLISECONDS) : Method waits for the result of the task atmost 100 milliseconds, If the wait time out, then get throws TimeoutException.

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.

Related Posts

Futute: Get result of the task                                                 Future: Cancel task execution                                                 Home

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

Future Interface

public interface Future<V>
A Future represents the result of an asynchronous computation. Future Interface provides methods to check if the computation of task is complete or not, to wait for task completion, and to retrieve the result of the computation and to cancel the task.

Method
Description
boolean cancel(boolean interrupt)
Attempts to cancel execution of this task.
V get()
Waits if necessary for the computation to complete, and then retrieves its result.
V get(long timeout, TimeUnit unit)
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
boolean isCancelled()
Returns true if this task was cancelled before it completed normally.
boolean isDone()
Returns true if this task completed.

Related Posts



callable vs runnable                                                 Future: Get result of the task                                                 Home