在使用Java7运行的Eclipse应用程序中,我遇到了当E4 ( 7 )关机或注销时不执行shutdown-hook的问题。
经过一些研究,我发现了下面的Open JDK bug entry,它创建了一个空的Swing JFrame并使用了一个关闭钩子。shutdown钩子创建一个文件并对其进行写入。尽管这个bug与我的问题没有直接关系,但我拿起代码并对其进行了一些修改(见下文)。(最大的修改是它不会在钩子中休眠。)
然后,我用该代码创建了一个jar,并用javaw -jar jarname.jar执行它。然后我尝试注销和关机,在这两种情况下都写入了预期的文件。
之后,我修改了代码,使其创建一个空的SWT Shell并使用相同的shutdown-hook (另请参阅下面的内容)。注销和关机时,不会写入预期的文件。
现在我想知道为什么行为如此不同?我发现特别难找到有关Windows和关机钩子的最新信息。
此外,如何确保在我的RCP应用程序中执行shutdown-hook?
Swing代码
public class ShutdownHookSwingBug {
public static final String fileName = "C:/shutdownhookbug_swing.log";
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
File myFile = new File(fileName);
myFile.delete();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
// Write "Hello " to a file
File myFile = new File(fileName);
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write("Hello ".getBytes());
outputStream.flush();
// Write "world!" and close the file
outputStream.write("world!".getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// Shouldn't happen.
}
}
});
}
}SWT代码
public class ShutdownHookSwtBug {
public static final String fileName = "C:/shutdownhookbug_swt.log";
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setSize(300, 300);
File myFile = new File(fileName);
myFile.delete();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
File myFile = new File(fileName);
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write("Hello ".getBytes());
outputStream.flush();
outputStream.write("world!".getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// Shouldn't happen.
}
}
});
shell.open();
while(!shell.isDisposed()){
if(!display.readAndDispatch()){
display.sleep();
}
}
display.dispose();
}
}发布于 2016-01-25 21:50:59
作为一种解决方法,我在我的E4 RCP应用程序中使用以下代码:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(false);
}
});但我对此并不满意,因为:
https://stackoverflow.com/questions/34994180
复制相似问题