x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    CompletableFuture example

    CompletableFuture was added in Java 8 which is superior to a Future. CompletableFuture allowes combining multiple asynchronous computations, reacting to an asynchronous tasks and graceful error handling.

    1) Below example shows CompletableFuture example using complete() call. Note that if you don't invoke complete() then CompletableFuture get() will be blocked forever.

    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutionException;
    
    public class CompletableFutureTaskExample {
        public static void main(String[] args) {
            CompletableFuture<Long> completableFuture = new CompletableFuture<>();
            Factorial task = new Factorial(10, completableFuture);
            Thread th = new Thread(task);
            th.start();
    
            long result = 0;
            System.out.println("Waiting to calculate factorial");
            try {
                result = completableFuture.get(); // blocking call
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
    
            System.out.printf("Wait over, factorial of 10 is %d", result);
        }
    }
    
    class Factorial implements Runnable {
        private long number;
        private CompletableFuture<Long> completableFuture;
    
        public Factorial(long number, CompletableFuture<Long> completableFuture) {
            this.number = number;
            this.completableFuture = completableFuture;
        }
    
        @Override
        public void run() {
            long fact = 1;
            for (long cnt = 1; cnt <= number; cnt++) {
                fact *= cnt;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            completableFuture.complete(fact);
        }
    }
    	

    Console Output :

    Waiting to calculate factorial
    Wait over, factorial of 10 is 3628800
    		

    2) Below example shows CompletableFuture example using runAsync() call to run a time consuming task asynchronously.

    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutionException;
    
    public class CompletableFutureTaskExample {
        public static void main(String[] args) {
            Factorial task = new Factorial(10);
            CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(task);
                
            while (!completableFuture.isDone()) {
                System.out.println("Waiting to calculate factorial");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
            }
    
            System.out.printf("Wait over, factorial is calculated");
        }
    }
    
    class Factorial implements Runnable {
        private long number;
    
        public Factorial(long number) {
            this.number = number;
        }
    
        @Override
        public void run() {
            long fact = 1;
            for (long cnt = 1; cnt <= number; cnt++) {
                fact *= cnt;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    	

    Console Output :

    Waiting to calculate factorial
    Waiting to calculate factorial
    Waiting to calculate factorial
    Waiting to calculate factorial
    Waiting to calculate factorial
    Waiting to calculate factorial
    Wait over, factorial is calculated
    		

    3) CompletableFuture supplyAsync() example

    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutionException;
    
    public class CompletableFutureTaskExample {
        public static void main(String[] args) {
            CompletableFuture completableFuture =
                CompletableFuture.supplyAsync(()-> "CompletableFuture example");
            try {
                System.out.println(completableFuture.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
                
            CompletableFuture completableFuture2 = CompletableFuture.supplyAsync(()-> 50);
            try {
                System.out.println(completableFuture2.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
    	

    Console Output :

    CompletableFuture example
    50
    		

    4) CompletableFuture thenApply() example

    package java8;
    
    import java.util.concurrent.CompletableFuture;
    
    public class CompletableFutureTaskExample {
        public static void main(String[] args) {
        	CompletableFuture cf = CompletableFuture.completedFuture("hello").thenApply(s -> {
        		return s.toUpperCase();
            });
        	System.out.println(cf.getNow(null));
                
        	CompletableFuture cf2 = CompletableFuture.completedFuture(10).thenApply(i -> {
        		return i*i;
            });
        	System.out.println(cf2.getNow(null));
                
        }
    }
    	
    	

    Console Output :

    HELLO
    100		

    5) Making multiple asynchronous calls in parallel using CompletableFuture. We can make multiple asynchronous calls by creating a Stream of CompletableFuture and then using CompletableFuture join which will retreive the final value after all tasks are executed.

    import java.util.List;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutionException;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class CompletableFutureTaskMultipleServicesJoin {
        public static void main(String[] args) {
    
            CompletableFutureTaskMultipleServicesJoin multipleServices 
                = new CompletableFutureTaskMultipleServicesJoin();
            long startTime = System.currentTimeMillis();
            System.out.println(multipleServices.getResponse());
            long endTime = System.currentTimeMillis();
            System.out.println("time elapsed in print method " 
                + (endTime - startTime) + " milliseconds");
        }
    
        private String getResponse() {
            CompletableFuture<String> completableFuture1 = CompletableFuture
                .supplyAsync(() -> service1());
            CompletableFuture<String> completableFuture2 = CompletableFuture
                .supplyAsync(() -> service2());
            CompletableFuture<String> completableFuture3 = CompletableFuture
                .supplyAsync(() -> service3());
    
            List<String> combined = Stream.of(completableFuture1, completableFuture2, completableFuture3)
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
    
            return combined.toString();
        }
    
        private String service1() {
            System.out.println("service 1 invoked");
            delay(1000);
            return "response1";
        }
    
        private String service2() {
            System.out.println("service 2 invoked");
            delay(2000);
            return "response2";
        }
    
        private String service3() {
            System.out.println("service 3 invoked");
            delay(3000);
            return "response3";
        }
    
        private void delay(long duration) {
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }

    Console Output :

    service 1 invoked
    service 2 invoked
    service 3 invoked
    [response1, response2, response3]


    References :
    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This