Future and FutureTask in java Last Updated : 08 Feb, 2023 Comments Improve Suggest changes Like Article Like Report Prerequisite: Future and callable Future: A Future interface provides methods to check if the computation is complete, to wait for its completion and to retrieve the results of the computation. The result is retrieved using Future's get() method when the computation has completed, and it blocks until it is completed. Future and FutureTask both are available in java.util.concurrent package from Java 1.5. FutureTask:FutureTask is a concrete implementation of the Future, Runnable, and RunnableFuture interfaces and therefore can be submitted to an ExecutorService instance for execution.When calling ExecutorService.submit() on a Callable or Runnable instance, the ExecutorService returns a Future representing the task. and one can create it manually also.FutureTask acts similar to a CountDownLatch when calling get() in that it waits for the task to complete or error out.Behaviour of the parameterless get() method depends on the state of the task. If tasks are not completed, get() method blocks until the task is completed. Once the task complete, it returns the result or throws an ExecutionException.An overloaded variant of get() allows passing a timeout parameter to limit the amount of time the thread waits for a result. Example: When submitting a FutureTask instance to a thread pool (ExecutorService instance) , it returns a Future object immediately. This Future object can be used for task completion and getting result of computation asynchronously. Examples: Create two task. After one is completely executed, then after waiting 2000 millisecond, second task is being executed Note: Online IDE does not work properly on sleep() method. Java // Java program do two FutureTask // using Runnable Interface import java.util.concurrent.*; import java.util.logging.Level; import java.util.logging.Logger; class MyRunnable implements Runnable { private final long waitTime; public MyRunnable(int timeInMillis) { this.waitTime = timeInMillis; } @Override public void run() { try { // sleep for user given millisecond // before checking again Thread.sleep(waitTime); // return current thread name System.out.println(Thread .currentThread() .getName()); } catch (InterruptedException ex) { Logger .getLogger(MyRunnable.class.getName()) .log(Level.SEVERE, null, ex); } } } // Class FutureTaskExample execute two future task class FutureTaskExample { public static void main(String[] args) { // create two object of MyRunnable class // for FutureTask and sleep 1000, 2000 // millisecond before checking again MyRunnable myrunnableobject1 = new MyRunnable(1000); MyRunnable myrunnableobject2 = new MyRunnable(2000); FutureTask<String> futureTask1 = new FutureTask<>(myrunnableobject1, "FutureTask1 is complete"); FutureTask<String> futureTask2 = new FutureTask<>(myrunnableobject2, "FutureTask2 is complete"); // create thread pool of 2 size for ExecutorService ExecutorService executor = Executors.newFixedThreadPool(2); // submit futureTask1 to ExecutorService executor.submit(futureTask1); // submit futureTask2 to ExecutorService executor.submit(futureTask2); while (true) { try { // if both future task complete if (futureTask1.isDone() && futureTask2.isDone()) { System.out.println("Both FutureTask Complete"); // shut down executor service executor.shutdown(); return; } if (!futureTask1.isDone()) { // wait indefinitely for future // task to complete System.out.println("FutureTask1 output = " + futureTask1.get()); } System.out.println("Waiting for FutureTask2 to complete"); // Wait if necessary for the computation to complete, // and then retrieves its result String s = futureTask2.get(250, TimeUnit.MILLISECONDS); if (s != null) { System.out.println("FutureTask2 output=" + s); } } catch (Exception e) { System.out.println("Exception: " + e); } } } } Outputpool-1-thread-1 FutureTask1 output = FutureTask1 is complete Waiting for FutureTask2 to complete Exception: java.util.concurrent.TimeoutException Waiting for FutureTask2 to complete Exception: java.util.concurrent.TimeoutException Waiting for FutureTask2 to complete Exception: java.util.concurrent.TimeoutException Waiting for FutureTask2 to complete pool-1-thread-2 FutureTask2 output=FutureTask2 is complete Both FutureTask Complete Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.htmlhttps://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html Comment More infoAdvertise with us Next Article Future and FutureTask in java R Rajput-Ji Follow Improve Article Tags : Java Technical Scripter Technical Scripter 2018 Java-Class and Object java-interfaces +1 More Practice Tags : JavaJava-Class and Object Similar Reads Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s 10 min read Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per 15+ min read Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it, 13 min read Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me 15+ min read Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an 13 min read Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac 15+ min read Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt 10 min read Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its 8 min read Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to 12 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read Like