What is java.util.concurrent.Future and Callable in thread concurrency in java


Contents of page :
  • Future<V> in java
    • V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
    • V get() throws InterruptedException, ExecutionException
    • cancel method
  • Callable<V> in java
    • V call() throws Exception;
    • How Callable and Future are related?
  • Program to demonstrate usage of Callable and Future in java>
  • Using <T> Future<T> submit(Runnable task, T result) and Future<?> submit(Runnable task) in program in java >


java.util.concurrent.Future<V> in java
Future interface provides methods in java >
  • for returning result of computation, wait until computation is not completed and
  • for cancelling the computation in between in java.

Future Methods in java >

V get() throws InterruptedException, ExecutionException;
Method returns the result of computation, method waits for computation to complete.

V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
Method waits for at most timeout time for computation to complete, and then returns the result, if available.

cancel method
method cancels the task.


java.util.concurrent.Callable<V> in java
Callable interface provides method for computing a result and returning that computed result or throws an exception if unable to do so
Any class implementing Callable interface must override call() method in java.

what type of results Callable’s call() method can return in java?
The Callable<V> is a generic interface, so its call method can return generic result spcified by V.


V call() throws Exception;
method for computing a result.
Method returns computed result or throws an exception if unable to do so.


How Callable and Future are related in java?
If you submit a Callable object to an Executor returned object is of Future type.

Future<Double> futureDouble=executor.submit(new SquareDoubleCallable(2.2));

This Future object can check the status of a Callable call’s method and wait until Callable’s call() method is not completed.

SquareDoubleCallable is a class which implements Callable.


Example/Program to demonstrate usage of java.util.concurrent.Callable and java.util.concurrent.Future in thread concurrency in java >
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;
class SumIntegerCallable implements Callable<Integer> {
   Integer n;
   SumIntegerCallable(Integer n) {
          this.n = n;
   }
   @Override
   public Integer call() throws Exception {
          Integer sum = 0;
          for (int i = 0; i <= n; i++) {
                 sum += i;
          }
          return sum;
   }
}
class SquareDoubleCallable implements Callable<Double> {
   Double n;
   SquareDoubleCallable(Double n) {
          this.n = n;
   }
   @Override
   public Double call() throws Exception {
          return n*n;
   }
}
public class CallableFutureExample {
 private static final int NTHREDS = 10;
 public static void main(String[] args) throws InterruptedException, ExecutionException {
   ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
   Future<Integer> futureInteger=executor.submit(new SumIntegerCallable(4));
   Future<Double> futureDouble=executor.submit(new SquareDoubleCallable(2.2));
  
   System.out.println("SumIntegerCallable has returned > "+futureInteger.get());
   System.out.println("SquareDoubleCallable has returned > "+futureDouble.get());
       
   executor.shutdown();
 }
}
/*OUTPUT
SumIntegerCallable has returned > 10
SquareDoubleCallable has returned > 4.840000000000001
*/

In the above program - we submit a Callable object to an Executor and returned object was of Future type.




Using <T> Future<T> submit(Runnable task, T result) and Future<?> submit(Runnable task) in program in java >

Let me brief you about both methods again-

<T> Future<T> submit(Runnable task, T result)
Submits a Runnable task for execution. Method returns a Future which represents that task. Once task is completed Future's get method will return the given result.

Future<?> submit(Runnable task)
Submits a Runnable task for execution. Method returns a Future which represents that task. Once task is completed Future's get method will return null.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyRunnable implements Runnable {
   @Override
   public void run() {
          System.out.println("MyRunnable's run()");
         
   }
}
public class SubmitRunnableExample {
 private static final int NTHREDS = 10;
 public static void main(String[] args) throws InterruptedException, ExecutionException {
   ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
   Future<Integer> futureInteger=executor.submit(new MyRunnable(), 1);
   System.out.println("futureInteger.get() > "+futureInteger.get());
    
   Future<?> future=executor.submit(new MyRunnable());
   System.out.println("future.get() > "+future.get());
 }
}
/*OUTPUT
MyRunnable's run()
futureInteger.get() > 1
MyRunnable's run()
future.get() > null
*/


Let’s analyze output -
when executor.submit(new MyRunnable(), 1) was called, it internally called call() method and on successful completion of MyRunnable’s run() method, futureInteger.get() returned 1, i.e. second parameter passed in submit method.
This type of submit method could be handy when in certain scenarios we want to return status of task.

when executor.submit(new MyRunnable()) was called, it internally called call() method and on successful completion of MyRunnable’s run() method, futureInteger.get() returned null.
    

    



RELATED LINKS>

Executor framework >

Executor and ExecutorService framework in java




Semaphore >

Semaphore in java

Implementation of custom/own Semaphore in java



Lock and Reentrant Locks >

Locks and ReEntrantLocks in java

ReentrantLock class provides implementation of Lock’s newCondition() method - description and solving producer consumer program using this method



ReadWriteLock and ReentrantReadWriteLock >

ReadWriteLock and ReentrantReadWriteLock in java



CountDownLatch >

CountDownLatch in java

Implementation of custom/own CountDownLatch in java



CyclicBarrier >

CyclicBarrier in java


No comments:

Post a Comment