Skip to main content

Command Palette

Search for a command to run...

Simplest Future and ExecutorService Example

Updated
1 min read
S

I love learning about technology and sharing that with others

Motivation

I was learning about asynchronous and reactive programming without even learning about Futures, Callable, ExecutorService and other stuff

Guide

  • this guide covers futures
  • here we have create CalculatorService which will do some compuitation and take some time so we will be returing the result in the future and in the caller method we will learn more on that how to handle future and the api associated with future it is really useful with asynchronous programming.
package com.example.movieservice;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class MovieserviceApplication {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
//        SpringApplication.run(MovieserviceApplication.class, args);

        System.out.println("hello world");


        SquareCalculator cal = new SquareCalculator();

        Future<Integer> future1= cal.calculate(10);
        Future<Integer> future2= cal.calculate(100);




        while (!(future1.isDone() && future2.isDone())) {
            System.out.println(
              String.format(
                "future1 is %s and future2 is %s", 
                future1.isDone() ? "done" : "not done", 
                future2.isDone() ? "done" : "not done"
              )
            );
            Thread.sleep(300);
        }



        Integer result= future1.get();
        Integer result2=future2.get();

        System.out.println(result + "   " +  result2);



    }



}

class SquareCalculator {

    private ExecutorService executor = Executors.newFixedThreadPool(2);

    public Future<Integer> calculate(Integer input) {


        return executor.submit( () -> {
            Thread.sleep(1000);
            return input*input;
        });




    }
}
15 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)