top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Java: Asynchronous Programming Using Completable Futures




Introduction:



In Java, the CompletableFuture class provides a way to perform asynchronous programming by allowing you to chain multiple tasks together and execute them concurrently.

A CompletableFuture is a type of Future that is used to represent the result of an asynchronous operation. It can be used to execute a task asynchronously, obtain the result of the task, and then perform additional tasks based on the result.


There are several other concurrency constructs like Semphore and Atomic Integers which you can checkout with examples.




Here is an example code that demonstrates the use of CompletableFuture to execute a task asynchronously and obtain its result:


public class CompletableFutureDemo {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, World!";
        });
        
        System.out.println("Waiting for future to complete...");
        
        future.thenAccept(result -> {
            System.out.println("Result: " + result);
        });
        
        System.out.println("Done!");
    }
}

In this example, we create a CompletableFuture object using the supplyAsync() method, which takes a Supplier lambda expression that represents the asynchronous task to be executed.

The lambda expression simulates a task that takes 2 seconds to complete by calling Thread.sleep(2000).

We then call the thenAccept() method on the future object, which takes a Consumer lambda expression that is executed when the future completes. The lambda expression prints the result of the task to the console.

Finally, we print "Done!" to the console to indicate that the main thread has finished executing.

Sample Output:


Waiting for future to complete...
Done!
Result: Hello, World!

As expected, the main thread prints "Waiting for future to complete..." and "Done!" to the console before the result of the asynchronous task is printed. This demonstrates how CompletableFuture can be used to execute tasks asynchronously and obtain their results.

8 views

Recent Posts

See All

Comments


bottom of page