How To Role Time To Come As Well As Futuretask Inwards Coffee Concurrency Amongst Example

Future as well as FutureTask inwards Java allows you lot to write asynchronous code. Future is a full general concurrency abstraction, also known equally a promise, which promises to render a consequence inwards future. In asynchronous programming, top dog thread doesn't aspect for whatsoever project to finished, rather it manus over the project to workers as well as movement on. One way of asynchronous processing is using callback methods. Future is simply about other way to write asynchronous code. By using Future and FutureTask, you lot tin write a method which does long computation but returns immediately. Those methods, instead of returning a result, return a Future object. You tin afterwards acquire the consequence yesteryear calling Future.get() method, which volition render an object of type T, where T is what Future object is holding.


One instance of Future is submit() method of ExecutorService, which similar a shot render a Future object. By the way, Future as well as FutureTask are available inwards java.util.concurrent packet from Java 1.5. Also, Future is as well as interface as well as FutureTask is an implementation or RunnableFuture, which tin hold upwards used equally a Runnable interface, thus, tin hold upwards passed to ExecutorService.

In this Java concurrency tutorial, nosotros volition acquire how to exercise Future as well as FutureTask inwards Java.



Future as well as FutureTask Example - Java

One of the simplest examples of using Future is working amongst Thread pools. When you lot submit a long running project to ExecutorService, it returns a Future object immediately. This Future object tin hold upwards used to query project completion as well as getting consequence of computation. In our sample Java program, nosotros convey a created a FactorialCalculator task, which wraps calculation of factorial nether Callable interface's call() method.

When nosotros submit this project amongst project of calculating factorial of a huge set out similar 100000, ExecutorService returns a Future object, which holds long value, render type of telephone telephone method inwards our case. Later, nosotros banking firm agree whether project is completed or non using isDone() method. From output, you lot tin run into that main thread returns immediately. Since nosotros convey used get() method 1 time project is completed, it doesn't block as well as render consequence immediately.

By the way, Future object returned yesteryear the submit() method is also an instance of FutureTask.

 Future as well as FutureTask inwards Java allows you lot to write asynchronous code How to exercise Future as well as FutureTask inwards Java Concurrency amongst Example




Sample Java Program to exercise Future as well as FutreTask
Here is our elementary seek program, which demonstrate how you lot tin exercise these 2 classes to create asynchronous execution inwards Java. First nosotros convey created a FutureTask which is naught but a nested static class which implements Callable interface. In this method nosotros telephone telephone our factorial method to calculate factorial of a number. To brand this method long-running, nosotros convey also introduced a small-scale slumber duration. This volition manage you lot to meliorate empathize how Future works.

package test;  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; import java.util.logging.Level; import java.util.logging.Logger;  /**  * Java programme to exhibit how to exercise Future inwards Java. Future allows to write  * asynchronous code inwards Java, where Future promises consequence to hold upwards available inwards  * hereafter  *  * @author Javin  */ public class FutureDemo {      private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);      public static void main(String args[]) throws InterruptedException, ExecutionException {          FactorialCalculator project = new FactorialCalculator(10);         System.out.println("Submitting Task ...");          Future hereafter = threadpool.submit(task);          System.out.println("Task is submitted");          while (!future.isDone()) {             System.out.println("Task is non completed yet....");             Thread.sleep(1); //sleep for 1 millisecond earlier checking again         }          System.out.println("Task is completed, let's banking firm agree result");         long factorial = future.get();         System.out.println("Factorial of meg is : " + factorial);          threadpool.shutdown();     }      private static class FactorialCalculator implements Callable {          private final int number;          public FactorialCalculator(int number) {             this.number = number;         }          @Override         public Long call() {             long output = 0;             try {                 output =  factorial(number);             } catch (InterruptedException ex) {                 Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);             }                          return output;         }          private long factorial(int number) throws InterruptedException {             if (number < 0) {                 throw new IllegalArgumentException("Number must hold upwards greater than zero");             }             long consequence = 1;             while (number > 0) {                 Thread.sleep(1); // adding delay for example                 consequence = consequence * number;                 number--;             }             return result;         }     }  }  Output Submitting Task ... Task is submitted Task is non completed yet.... Task is non completed yet.... Task is non completed yet.... Task is completed, let's banking firm agree consequence Factorial of meg is : 3628800

You tin run into that because of the sleep() method nosotros convey introduced inwards factorial method, it took simply about fourth dimension to terminate as well as during that fourth dimension isDone() method returned false. This is why you lot are seeing the output "Task is non completed yet". Once project is completed the consequence is available equally Future object.

See Core Java for Inpatients to acquire to a greater extent than almost how to exercise concurrency classes inwards Java Program.

 Future as well as FutureTask inwards Java allows you lot to write asynchronous code How to exercise Future as well as FutureTask inwards Java Concurrency amongst Example



Important points Future as well as FutureTask  in Java

Now nosotros convey learned how to exercise Future as well as FutureTask inwards Java program. Let's revise simply about fundamental points almost Future concept as well as FutureTask shape inwards Java itself.

1. Future is a base of operations interface as well as defines abstraction of an object which promises consequence to hold upwards available inwards hereafter acre FutureTask is an implementation of the Future interface.

2. Future is a parametric interface as well as type-safe written equally Future<V>, where V denotes value.

3. Future provides get() method to acquire result, which is blocking method as well as blocks until consequence is available to Future.

4. Future interface also defines cancel() method to cancel task.

5. isDone() as well as isCancelled() method is used to query Future project states. isDone() returns true if project is completed as well as consequence is available to Future. If you lot telephone telephone get() method, after isDone() returned true then it should render immediately. On the other hand, isCancelled() method returns true, if this project is cancelled earlier its completion.

6. Future has iv sub interfaces, each amongst additional functionality e.g. Response, RunnableFuture, RunnableScheduledFuture and ScheduledFuture. RunnableFuture also implements Runnable as well as successful terminate of run() method drive completion of this Future.


7. FutureTask as well as SwingWorker are 2 good known implementation of Future interface. FutureTask also implements RunnableFuture interface, which agency this tin hold upwards used equally Runnable as well as tin hold upwards submitted to ExecutorService for execution.


8. Though most of the fourth dimension ExecutorService creates FutureTask for you, i.e. when you lot submit() Callable or Runnable object. You tin also created it manually.


9. FutureTask is commonly used to roll Runnable or Callable object as well as submit them to ExecutorService for asynchronous execution.


That's all on How to exercise Future as well as FutureTask inwards Java. Understanding concept behind Future is really of import for writing asynchronous code inwards Java. In elementary words, Future allows whatsoever method to render immediately, amongst hope of consequence existence available inwards future. By using this technique your top dog thread tin create other things acre waiting for sure enough project to hold upwards completed.

Further Learning
Multithreading as well as Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
Applying Concurrency as well as Multi-threading to Common Java Patterns
Java Concurrency inwards Practice Course yesteryear Heinz Kabutz


0 Response to "How To Role Time To Come As Well As Futuretask Inwards Coffee Concurrency Amongst Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel