I am writing a server-client application in Java, and I want the server to send a message to the client in the event that it crashes or shuts down unexpectedly.
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
out.writeObject(new ServerQuit());
out.close();
}
}
where out
is the output stream used to write to the client, and ServerQuit
represents the message sent when the server crashes.
Is this safe to do? Javadocs says that one should not "rely blindly upon services that may have registered their own shutdown hooks and therefore may themselves in the process of shutting down." Since I/O streams automatically close when the JVM is shut down, will my shutdown hook work? That is, at the time shutdown hooks run, will I/O streams have already closed?