Reputation: 926
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?
Upvotes: 2
Views: 1621
Reputation: 310980
I/O streams don't 'automatically close when the JVM is shut down'. The operating system closes any files and sockets etc that the process may have left open, but this has nothing to do with any action by the JVM. Therefore at the time the shutdown hook runs, your stream is still open.
However What you're doing is completely unnecessary. The client will receive an end of stream in any case. That's all it needs.
Upvotes: 0