Tuesday, January 24, 2017

java: cleaning / logging before shutdown

1. Use a Shutdown Hook

If you would like to shutdown some connections, restore resources, or print a log message before your program is shut down, you may use the Shutdown hook to achieve it.

public class CleanTest {
      private String name;

      public CleanTest(String name){
            this.name = name;

            Runtime.getRuntime().addShutdownHook(new Thread() {
                 public void run() {
                        Log.write("CleanTest is shutting down....");
                       //shutdown connections
                       //restore resources
                }
         });
    }
}

2. Use a Window Listener

If you are executing a java.awt.Window object such as JFrame and JDialog, you can add a java.awt.event.WindowListener to do the job.

public class CleanTest extends JFrame {
    private String name = "";
 
    public CleanTest (String name) {
        this.name = name;
        //Build your window components
     
        setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e){
                //shutdown connections
                //restore resources
            }
        });

        pack();
        setVisible(true);
    }


---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment