×

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

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.