2

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?

jedyobidan
  • 876
  • 1
  • 8
  • 14
  • I'm pretty sure in the case of a crash the server would just *stop*. Can't really rely on anything for a crash. idk about a shutdown though... – awksp May 19 '14 at 23:34

1 Answers1

0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • So it would be unnecessary to send the ServerQuit message, but one should probably close the socket right? – jedyobidan May 20 '14 at 01:50
  • You should close the `ObjectOutputStream` if there is a `BufferedOutputStream` underneath it, to ensure flushing. Otherwise just forget about it. – user207421 May 20 '14 at 02:40
  • @EJP - What about standard Input stream (System.in)? . Suppose I have created a scanner pointing to System.in, if I don't call `scanned.close()` in the end, what will happen? – TheLostMind Jun 08 '15 at 09:25