Created
August 11, 2017 12:38
-
-
Save rainsunny/007ebb70cd46e8f1031aac5f181b9d30 to your computer and use it in GitHub Desktop.
Java application graceful shutdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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