0

I have a very basic question regarding java application servers running on Eclipse. I would like to execute some code when the admin wishes to stop the server, so I am looking for a function that is called when the "stop" button on the console is pressed by the admin.

The application server is running fine but I would like to clear the state of my database after the server is stopped. The code for my server is given below:

public static void main(String[] args){
   try{
       while(true){
           Socket s=listener.accept();
           //do other stuff here
       }}
   //catch blocks
   try{
       listener.close();
    }
    //catch block
    System.out.println("Server stopped");
  }

However, the statement "server stopped" is never printed on the screen. Could anyone please tell which function is explicitly called when the server is stopped?

Thanks in advance.

BajajG
  • 2,134
  • 2
  • 25
  • 32

1 Answers1

-1

Combine calling ServerSocket.close() in this answer with shutdown hooks in this answer.

For example, you would do:

public class Main {

    private static volatile boolean keepRunning = false;

    public static void main(String[] args){
        final ServerSocket listener = ... ;
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                keepRunning = false;
                listener.close();
                mainThread.join();
            }
        });

        try {
            while (keepRunning) {
                Socket s=listener.accept();
                //do other stuff here
            }
        } catch (Exception e) {
        }
        // Do cleanup here
        System.out.println("Server stopped");
    }
}

Then when you either a) issue a Ctrl-C or b) call System.exit(), it will call your shutdown hook, which closes the ServerSocket, which interrupts ServerSocket.accept() and causes it to throw a SocketException, and then it will print Server Stopped.

Neat fact: the mainThread.join() line will make the stop command wait until the program fully exits before actually terminating, allowing all your cleanup to happen.

Edit: Sorry for all the edits, getting back into the swing of SO.

Community
  • 1
  • 1
Brian
  • 17,079
  • 6
  • 43
  • 66