I'm trying to shutdown my server using a ctrl-c keyboard shortcut and I searched for some way to do this and found this post.
I tried this solution, but when the shutdown hook finishes, my main thread also ends up without complete the server shutdown tasks and the process finishes with code 1.
Here is my code:
package test;
import java.io.IOException;
import java.net.ServerSocket;
public class Main implements Runnable {
private ServerSocket serverSocket;
private Main() {
try {
serverSocket = new ServerSocket(5000);
} catch (IOException e) {
e.printStackTrace();
System.exit(10);
}
System.err.println("Waiting ctrl-c ...");
Runtime.getRuntime().addShutdownHook(new Thread(this));
try {
while (serverSocket.accept() != null) {
doSomething();
}
System.err.println("end while");
} catch (IOException e) {
System.err.println("end exception");
} finally {
System.err.println("trying to close the server...");
try {
// simulate a long job
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// this line was never reached
System.err.println("server closed");
}
}
public static void main(String[] args) {
new Main();
}
private void doSomething() {}
@Override
public void run() {
System.err.println("ctrl-c pressed");
try {
System.err.println("trying to close socket");
serverSocket.close();
System.err.println("socket closed!!!");
} catch (IOException e) {
System.err.println("failed to close socket");
}
}
}
Here is the output from inside IntelliJ IDE:
Waiting ctrl-c ...
ctrl-c pressed
trying to close socket
socket closed!!!
end exception
trying to close the server...
Process finished with exit code 1
How do I, elegantly, fix this problem?