1. pExecutorService.shutdown(); 2. try { 3. if (!pExecutorService.awaitTermination(pTimeout, TimeUnit.SECONDS)) { 4. pExecutorService.shutdownNow(); 5. } 6. catch (final InterruptedException pCaught) { 7. pExecutorService.shutdownNow(); 8. Thread.currentThread().interrupt(); 9. } 10. }First we invoke the shutdown method on the executor service. After this point, no new runnables will be started.
The next step is to wait for already running tasks to complete. In this example we will allow the running tasks to complete within pTimeout seconds. If they don't complete within the given amount of seconds, we invoke shutdownNow(). This method will invoke interrupt on all still running threads.
As a good practice we also make sure to catch InterrruptedException's and shutdown everything immediately.
Thanks for helpful tutorial. Can you explain why we need: Thread.currentThread().interrupt();
ReplyDeleteyou can check out the reason here: http://www.javamex.com/tutorials/threads/thread_interruption_2.shtml#InterruptedException
Delete