Search code examples
javamultithreadingjava.util.concurrent

The execution of the program doesn't end though the program executed successfully when using threads


I am exploring java.util.concurrent.* Calculating the square and waiting using Thread.sleep(5000) , the program works as expected, but never terminates.

The red square in eclipse is "ON", that we usually use to terminate the program.

Can you please help in understanding why the program doesn't terminate on completion??



    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // TODO Auto-generated method stub
        try {
        SquareCalculator sqC = new SquareCalculator();
        sqC.display(1);
        Future<Integer> result = sqC.calculate(5);

        while(!result.isDone())
        {
            System.out.println("Waiting for the calculation");
            Thread.sleep(1000);
            //result.cancel(true);
        }
        Integer square = result.get();
        System.out.println(square);
        }catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("Calclulation was interrupted");
        }
    }

public class SquareCalculator {

    private ExecutorService ex = Executors.newSingleThreadExecutor();

    public void display(int i) {
        // TODO Auto-generated method stub
        System.out.println(i);
    }

    public Future<Integer> calculate(Integer inp)
    {
        try {
            System.out.println("Before sending request");
        Future<Integer> res = ex.submit(()->{

            Thread.sleep(5000);
            return inp*inp;
        });
        System.out.println("Request sent to caluclate and waiting for the result");
        return res;
        }catch(Exception e)
        {
            System.out.println("calculation was interrupted");
            return null;
        }
        //return ex.submit(()->squareing(inp));

    }

}

OUTPUT

1
Before sending request
Request sent to caluclate and waiting for the result
Waiting for the calculation
Waiting for the calculation
Waiting for the calculation
Waiting for the calculation
Waiting for the calculation
25

Solution

  • You need to refactor your code and return the object instead of Future. You should also shutdown executor when you are done.

    
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class SquareCalculator {
    
        private ExecutorService ex = Executors.newSingleThreadExecutor();
    
        public void display(int i) {
            // TODO Auto-generated method stub
            System.out.println(i);
        }
    
        public Integer calculate(Integer inp) {
            Integer result;
            try {
                System.out.println("Before sending request");
                Future<Integer> res = ex.submit(() -> {
                    Thread.sleep(5000);
                    return inp * inp;
                });
                System.out.println("Request sent to caluclate and waiting for the result");
                result = res.get();
                ex.shutdown();
                return result;
            } catch (Exception e) {
                System.out.println("calculation was interrupted");
                return null;
            }
            //return ex.submit(()->squareing(inp));
    
        }
    
        public static void main(String[] args) throws InterruptedException, 
            ExecutionException {
            // TODO Auto-generated method stub
            try {
                SquareCalculator sqC = new SquareCalculator();
                sqC.display(1);
                Integer result = sqC.calculate(5);
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("Calclulation was interrupted");
            }
        }
    }