@Test
public void gracefulShutdown() throws InterruptedException {
Logger logger = LoggerFactory.getLogger("test");
MockLog4jAppender appender = new MockLog4jAppender();
appender.addToLogger("test");
//time enough to shutdown
ExecutorService pool = Executors.newSingleThreadExecutor();
Runnable task = new Task(logger, 500, 0);
pool.execute(task);
ThreadUtils.gracefulShutdown(pool, 1000, 1000, TimeUnit.MILLISECONDS);
assertTrue(pool.isTerminated());
assertNull(appender.getFirstLog());
//time not enough to shutdown,call shutdownNow
appender.clearLogs();
pool = Executors.newSingleThreadExecutor();
task = new Task(logger, 1000, 0);
pool.execute(task);
ThreadUtils.gracefulShutdown(pool, 500, 1000, TimeUnit.MILLISECONDS);
assertTrue(pool.isTerminated());
assertEquals("InterruptedException", appender.getFirstLog().getMessage());
//self thread interrupt while calling gracefulShutdown
appender.clearLogs();
final ExecutorService self = Executors.newSingleThreadExecutor();
task = new Task(logger, 100000, 0);
self.execute(task);
final CountDownLatch lock = new CountDownLatch(1);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
lock.countDown();
ThreadUtils.gracefulShutdown(self, 200000, 200000, TimeUnit.MILLISECONDS);
}
});
thread.start();
lock.await();
thread.interrupt();
ThreadUtils.sleep(500);
assertEquals("InterruptedException", appender.getFirstLog().getMessage());
}