[英]Different shutdown-hook behavior on Windows shutdown
在使用Java 7運行的Eclipse E4 RCP應用程序中,我遇到的問題是,當Windows(7)關閉或注銷時,不會執行shutdown-hook。
經過一些研究后,我發現了以下Open JDK錯誤條目 ,它創建了一個空的Swing JFrame並使用了一個shutdown-hook。 關閉鈎子創建一個文件並寫入它。 雖然這個bug與我的問題沒有直接關系,但我接受了代碼並對其進行了一些修改(見下文)。 (最大的修改是它不會陷入困境。)
然后我從該代碼創建了一個jar並用javaw -jar jarname.jar
執行它。 然后我嘗試注銷並關閉,在這兩種情況下都寫入了預期的文件。
之后我修改了代碼,以便創建一個空的SWT Shell並使用相同的shutdown-hook(另見下文)。 注銷和關閉時,不會寫入預期的文件。
現在我想知道為什么行為如此不同? 我發現特別難以找到有關Windows和關機鈎子的最新信息。
此外,如何確保在我的RCP應用程序中執行shutdown-hook?
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.
}
}
});
}
}
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();
}
}
作為一種解決方法,我在E4 RCP應用程序中使用以下代碼:
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(false);
}
});
但我不滿意,因為:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.