Shutdown hooks provide a mechanism to ensure that Java applications perform necessary cleanup tasks before gracefully exiting. In this article, we'll delve into the practical application of shutdown hooks, exploring a scenario where we want to ensure data is flushed to a file before program termination.
Consider the following Java application:
<code class="java">package com.example.test.concurrency; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; public class GracefulShutdownTest1 { final private int N; final private File f; public GracefulShutdownTest1(File f, int N) { this.f=f; this.N = N; } public void run() { PrintWriter pw = null; try { FileOutputStream fos = new FileOutputStream(this.f); pw = new PrintWriter(fos); for (int i = 0; i < N; ++i) writeBatch(pw, i); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { pw.close(); } } // Write a batch of numbers to the file private void writeBatch(PrintWriter pw, int i) { for (int j = 0; j < 100; ++j) { int k = i*100+j; pw.write(Integer.toString(k)); if ((j+1)%10 == 0) pw.write('\n'); else pw.write(' '); } } public static void main(String[] args) { if (args.length < 2) { System.out.println("args = [file] [N] " +"where file = output filename, N=batch count"); } else { new GracefulShutdownTest1( new File(args[0]), Integer.parseInt(args[1]) ).run(); } } }</code>
In this application, we write batches of numbers to a file. To ensure that a batch is finished before the program is interrupted, we'll use a shutdown hook.
To integrate a shutdown hook, follow these steps:
Here's an example:
Add a keepRunning variable:
<code class="java">final static volatile boolean keepRunning = true;</code>
Modify the run() method:
<code class="java">//... for (int i = 0; i < N && keepRunning; ++i) writeBatch(pw, i); //...</code>
Add the shutdown hook in main():
<code class="java">//... Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { keepRunning = false; mainThread.join(); } }); //...</code>
When the JVM receives a shutdown signal (e.g., Ctrl C), the shutdown hook will set keepRunning to false. The run() method will then continue writing data until keepRunning is false, ensuring that the current batch is finished before the program exits.
The above is the detailed content of How Can Shutdown Hooks Ensure Graceful Program Termination in Java?. For more information, please follow other related articles on the PHP Chinese website!