Skip to content

Instantly share code, notes, and snippets.

@rainsunny
Created August 11, 2017 12:38
Show Gist options
  • Save rainsunny/007ebb70cd46e8f1031aac5f181b9d30 to your computer and use it in GitHub Desktop.
Save rainsunny/007ebb70cd46e8f1031aac5f181b9d30 to your computer and use it in GitHub Desktop.
Java application graceful shutdown
ESRunner runner = new ESRunner();
// Gracefully shutdown
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
runner.shutdown(); // Clean up work
mainThread.join(200); // wait main thread to stop
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
runner.run();
// In ESRunner:
private final AtomicBoolean closed = new AtomicBoolean(false);
public void run() {
try {
while (!closed.get()) {
// Doing stuff
}
} catch (WakeupException e) {
// Ignore exception if closing
if (!closed.get()) throw e;
} finally {
consumer.close();
client.close();
}
}
// Shutdown hook which can be called from a separate thread
public void shutdown() {
log.info("Shutting down es runner");
closed.set(true);
consumer.wakeup();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment