0

The problem with this is that, since the method "process()" takes quite a while to complete with 10 threads, the tt.shutdownService() got immediately executed. How to ensure the shutdownService() is executed after other threads, i.e. after the process() is executed?

public class ThreadTest{

  private ExecturoService service;

  void main(String[] args){
      long startTime = System.currentTimeLillis();

       ThreadTest tt = new ThreadTest();
       tt.process();

       tt.shutdownService();

      long endTime = System.currentTimeLillis();
  }

   public ThreadTest(){
      service = Executors.newFixedThreadPool(10);
   }
   public void process(){
        ...
        service.execute(new Runnable){...}
   }

   public void shutdownService(){
       if(service != null){
           service.shutdown();
           service.awaitTermination(60, TimeUnit.SECONDS);
       }
   }
}

Note, my actual program is a little more complex. I can't shutdown the service in process(), since process() will be called multiple times in a loop. Here I simplified the case.

user697911
  • 9,271
  • 20
  • 83
  • 153

2 Answers2

0

As per Javadocs

This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

Scary Wombat
  • 43,525
  • 5
  • 33
  • 63
0

What you are looking for is awaitTermination. This code will actually wait until all the tasks finish. Or until pretty much the end of time, whatever happens first.

executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
Tavo
  • 2,907
  • 4
  • 27
  • 44