Jas*_*n S 121 java shutdown-hook
我正在努力确保我的Java应用程序采取合理的步骤来保持健壮,其中一部分涉及优雅地关闭.我正在阅读有关关闭钩子的事情,我实际上并没有在实践中如何使用它们.
那里有一个实际的例子吗?
Let's say I had a really simple application like this one below, which writes numbers to a file, 10 to a line, in batches of 100, and I want to make sure a given batch finishes if the program is interrupted. I get how to register a shutdown hook but I have no idea how to integrate that into my application. Any suggestions?
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();
}
}
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(' ');
}
}
static public 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 155
您可以执行以下操作:
.interrupt工作线程,如果他们在某些阻塞调用中等待数据)writeBatch通过调用Thread.join()工作线程上的方法,等待工作线程(在您的情况下执行)完成.一些粗略的代码:
static volatile boolean keepRunning = true;在run()中,您将更改为
for (int i = 0; i < N && keepRunning; ++i)
writeBatch(pw, i);
Run Code Online (Sandbox Code Playgroud)在main()中添加:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
keepRunning = false;
mainThread.join();
}
});
Run Code Online (Sandbox Code Playgroud)这大致是我在终端中如何优雅地"在击中Control-C时拒绝所有客户".
来自文档:
当虚拟机开始其关闭序列时,它将以某种未指定的顺序启动所有已注册的关闭挂钩,并让它们同时运行.当所有挂钩都完成后,如果启用了finalization-on-exit,它将运行所有未读取的终结器.最后,虚拟机将停止.
也就是说,一个关闭钩子使JVM保持运行,直到钩子终止(从run() -method 返回).
| 归档时间: |
|
| 查看次数: |
132392 次 |
| 最近记录: |