@Test
public void gracefulShutdown() throws InterruptedException {
Logger logger = LoggerFactory.getLogger("test");
LogbackListAppender appender = new LogbackListAppender();
appender.addToLogger("test");
// time enough to shutdown
ExecutorService pool = Executors.newSingleThreadExecutor();
Runnable task = new Task(logger, 500, 0);
pool.execute(task);
Threads.gracefulShutdown(pool, 1000, 1000, TimeUnit.MILLISECONDS);
assertThat(pool.isTerminated()).isTrue();
assertThat(appender.getFirstLog()).isNull();
// time not enough to shutdown,call shutdownNow
appender.clearLogs();
pool = Executors.newSingleThreadExecutor();
task = new Task(logger, 1000, 0);
pool.execute(task);
Threads.gracefulShutdown(pool, 500, 1000, TimeUnit.MILLISECONDS);
assertThat(pool.isTerminated()).isTrue();
assertThat(appender.getFirstLog().getMessage()).isEqualTo("InterruptedException");
// 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();
Threads.gracefulShutdown(self, 200000, 200000, TimeUnit.MILLISECONDS);
}
});
thread.start();
lock.await();
thread.interrupt();
Threads.sleep(500);
assertThat(appender.getFirstLog().getMessage()).isEqualTo("InterruptedException");
}