-1

I have a simple http server implemented with thread pool. I want to shut down the server gracefully. I referred the post Best Way to Gracefully Shutdown a Java Command Line Program Here is the basic code:

 public static void main(String[] args) {
    ThreadPoolServer threadserver = new ThreadPoolServer(9000);
    new Thread(threadserver).start();
    threadserver.attachShutDownHook();
    while (true) {
        try {
            Thread.sleep(20 * 10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public synchronized void stopthread(){
    this.shutdown = true;
    try {
        this.serverSocket.close();
    } catch (IOException e) {
        throw new RuntimeException("Error closing server", e);
    }
}

public synchronized void attachShutDownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            stopthread();
        }
    });
}

But it seems it does not stop the right way, any ideas? Thx.

Community
  • 1
  • 1
printemp
  • 869
  • 1
  • 10
  • 33

1 Answers1

0

This is too small piece of code.

But at the first sight I don't see any check for shutdown value in the main while loop. Secondly the variable should be set after and probably join on the listening thread would be worthy. In the run method I assume you properly handle the exception raised by asynchronous close.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43