×

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 Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 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.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 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.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.