Problem:
gcj / gij do not execute ShutdownHooks registered with Runtime.getRuntime().addShutdownHook() if the program is stopped by pressing CTRL-C. ShutdownHooks are executed only on a normal exit (reaching the end of main() or explicit calling System.exit(int status).
(As far as I can see this is a common problem of all free VMs like kaffe, sablevm.)
The developer of JamVM, Robert Lougher, announced me that he fixed this for JamVM since 1.3.2.
A simple test-class I used looks like:
public class ShutdownHookTest {
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
System.out.println("shutting down ...");
for(int i = 10; i>0; i--){
System.out.println(i);
try{
Thread.sleep(500);
}catch(InterruptedException e){
System.err.println(e.getMessage());
}
}
System.out.println("shutdown finished!");
}
}));
while (true){
System.out.print(".");
System.out.flush();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.err.println(e.getMessage());
}
}
}
}
You can download it here
Patch:
Here is a simple patch for libjava, solving the problem.
I tested it with gcc 4.0.1 on ix86-pc-linux-gnu (but it should work with other versions and on other target-systems).
The patch will have no effect on MinGW-builds of gcj/gij, as Windows has no POSIX-compilant signal-handling!
You can apply the patch in the src-dir of gcc:
patch -p0 < ../gcj-4.0.1.patch
Differences to Suns java:
If you use the java-class above with suns java, you can see that the main()-funktion is still running while the shutdownHook is run. Using gcj/gij, this is not the case!
ToDo:
If I find the time, I will try to improve the patch ...