Form do not disappear on closing java application

231 Views Asked by At

I created a hook that excute some operation when the form is closed:

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            System.out.println("In shutdown hook");
            String dataCrittare = "lgt%";
            Date now=new Date();
            SimpleDateFormat dateformat = new SimpleDateFormat ("yyyyMMdd-HHmm");
            writer.println(dateformat.format(now));
            writer.flush();
            System.out.println("arrived?");
            dispose();
            System.exit(1);

        }
     }, "Shutdown-thread"));

It seems that the program exit, but remains the form blocked on the screen, and i have to close it brutally. Anyone know why the form do not disappear? Thanks

1

There are 1 best solutions below

2
On

The shutdown hooks get invoked when System.exit() is called. You shouldn't call System.exit() inside your shutdown hook since the JVM is already on its way to termination. Inside addShutdownHook(), the call to System.exit() deadlocks at Shutdown.exit() (which is called from System.exit()). Even the comment there says:

        /* Synchronize on the class object, causing any other thread
         * that attempts to initiate shutdown to stall indefinitely
         */

Your shutdown hook does not get called on form closing! (Except you have some JFrame.setDefaultCloseOperation(EXIT_ON_CLOSE) or so.)