Link to home
Start Free TrialLog in
Avatar of Jay Roy
Jay RoyFlag for United States of America

asked on

ExecutorService shutdownAndAwaitTermination()

hi guys

Was reading up the ExecutorService API
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

Was trying to understand what shutdownAndAwaitTermination() method does and
do we need to use it everytime we use ExecutroService?

Below is my scenario
 
...
...
executor.submit(myTask); --> i am submitting task to executor
...
shutdownAndAwaitTermination(executor); -- finally i am calling shutdownAndAwaitTermination()
...
...


//taken from java doc
shutdownAndAwaitTermination(ExecutorService pool)
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown();//once the above task has been executed by threads,shut down executor ?
 try {
     // Wait 60 seconds  for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {  //--what does this do?    
     pool.shutdownNow(); // Cancel currently executing tasks
       
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     Thread.currentThread().interrupt();--what does this do?
   }
 }
ASKER CERTIFIED SOLUTION
Avatar of nareshvoota
nareshvoota
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jay Roy

ASKER

thanks,
I find it little confusing.
You say
>>If another thread called interrupt on this thread, pool.awaitTermination will throw Interrupted exception and clears the interrupted status on the thread

static boolean interrupted() method clears the interrupted status and not the void interrupt() method, correct?

My question is in comments:

--taken from java doc
shutdownAndAwaitTermination(ExecutorService pool)
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown();
 try {    
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {  //this is a blocking method, so   an interrupted exception is thrown, correct?  
     pool.shutdownNow();        
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     Thread.currentThread().interrupt();  // Most importantly i want to know what does this do?
   }
 }

If you can tell me what happens step - by - step that will be great.

thanks