2

Given the following Java example, which uses multithreading:

 import java.util.concurrent.*;

 public class SquareCalculator {
     private ExecutorService executor = Executors.newSingleThreadExecutor();

     public Future<Integer> calculate(Integer input) {
         return executor.submit( () -> {
             Thread.sleep(1000);
             return input * input;
         });
     }

     public static void main(String[] args) {
         try {
             Future<Integer> future = new SquareCalculator().calculate(10);
             while (!future.isDone()){
                 System.out.println("Calculating...");
                 Thread.sleep(300);
             }

             Integer result = future.get();
             System.out.println("we got: " + result);
         } catch(InterruptedException | ExecutionException e) {
             System.out.println("had exception");
         }
     }
 }

It produces:

java SquareCalculator
Calculating...
Calculating...
Calculating...
Calculating...
we got: 100

But the application is never terminating.

Am I suppose to join the thread or something?

jgp
  • 2,069
  • 1
  • 21
  • 40
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • What do you mean by "it's not returning the prompt"? Can please explain a bit more. – Amit Bera Feb 04 '19 at 18:20
  • @AmitBera my shell is not returning to me as if program is still running. i have to ctrl+c to get it back and to be able to interact with shell again – ealeon Feb 04 '19 at 18:22

3 Answers3

3

Should be in comment but not enough reputation.

You should call shutdown on executor. You can get more details from below link: Reason for calling shutdown() on ExecutorService

3

I bet you want to add something like this:

   finally {
        if (executor != null) {
            executor.shutdown();
        }
    }
automatictester
  • 2,436
  • 1
  • 19
  • 34
2

You need to shut down the executor framework towards the end of the program and wait until it gracefully terminates..

executor.shutdown();
try {
    executor.awaitTermination(4 * 3600, TimeUnit.SECONDS);
} catch (Exception e) {
    e.printStackTrace();
}
VHS
  • 9,534
  • 3
  • 19
  • 43