×

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation is finished, the result is retrieved using the Future's get() method, and the computation stalls until it is finished. Future and FutureTask are both included in the Java 1.5 java.util.concurrent package.

Future Inteface()  Methods

MethodDescription
cancel()It tries to halt the task's execution
get()Receives the result after, waiting for the computation to finish.
isCancelled()    If the task was stopped before it finished, the isCancelled() function returns true.
isDone()The isDone() function returns true if the work has been finished.

Getting Result

Future is what an asynchronous task produces. The Java Future interface provides the following two iterations of the get() method, both of which return an object to receive the outcome of that asynchronous task.

Syntax

Object r = f.get(); 

Cancel Asynchronous task

Using the cancel() function of the Future interface, we can end an asynchronous job at any time.

Syntax

Future future = ret;
future.cancel();  

Verify if an asynchronous task has been completed

The interface offers the isDone() method to determine whether or not the asynchronous task has been finished.

Syntax

Future future = ... 
if(future.isDone())   
{  
    Object result = future.get();  
}   

Check if an Asynchronous Task is Cancelled

The isCancelled() method of the Future interface can be used to determine whether or not the asynchronous job that Future represents has been cancelled. If the task is successfully canceled, it returns true; otherwise, it returns false.

Syntax

Future future = ...   
if(future.isCancelled())   
{  
}
  • FutureTask implements the Future interface and the RunnableFuture interface, allowing it to be used as a runnable and sent to the ExecutorService for execution.
  • ExecutorService typically creates FutureTasks when Callable or Runnable objects are called with Future. submit(), but it is also possible to manually construct FutureTasks.
  • FutureTask functions as a latch.
  • FutureTask's computation model is built using the Callable interface.
  • The Future or Callable interface is implemented.
  • The task's state affects how the get() method behaves. If tasks are not finished, the get() method waits or blocks until they are. When a job is finished, it returns the outcome or raises an ExecutionException.

Java program for Future Example

FutureExample.java

// import required packages
import java . util . concurrent . * ;
import java . util . logging . Level ;
import java . util . logging . Logger ;


class R1 implements Runnable {
//
private final long wt ;


public R1 ( int time )
{
this.wt= time ;
}


@Override
public void run ( )
{
try {
Thread . sleep ( wt ) ;


System . out . println ( Thread . currentThread() . getName () ) ;
}


catch ( InterruptedException ex) {
Logger . getLogger ( R1 . class . getName () ) . log ( Level . SEVERE ,null , ex ) ;
} 
}
}


class FutureExample {


public static void main ( String[] args )
{
R1 runnable1 = new R1 ( 1000 ) ;
R1 runnable2 = new R1 ( 2000 ) ;


FutureTask <String> ft1 = new FutureTask <> ( runnable1 ," FutureTask1 is complete " ) ;
FutureTask <String> ft2 = new FutureTask <> ( runnable2 ,"FutureTask2 is complete " ) ;
ExecutorService exe = Executors . newFixedThreadPool ( 2 ) ;
exe . submit ( ft1 ) ;
exe . submit ( ft2 ) ;


while (true) {
try {
if (ft1.isDone() && ft2.isDone()) {


System.out.println("Both FutureTask Complete");
exe.shutdown();
return;
}


if (!ft1.isDone()) { 
System.out.println(" output of futureTask1 = "+ ft1.get());
}


System.out.println( "FutureTask2 to complete Waiting  " ) ;
String str = ft2 . get ( 250 , TimeUnit . MILLISECONDS ) ;


if (str != null) {
System . out . println ( " Output of FutureTask2 = " + str ) ;
}
}


catch ( Exception ex ) {
System . out . println ( " Exception: " + ex ) ;
}
}
}
}

Output:

Java Future Example

Related Topics

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.