running code when the program closes
I have a server that has a main loop listed below:
while (listening)
{
new ServerThread(serverSocket.accept()).start();
}
The only way I have to stop the server is to manually close it, because the serversocket.accept() method blocks until a connection is made. I would like to be able to execute some code before I close the server, such as saving things to a file. However, I can't do this because I'm closing the program manually. I came up with a solution where the program has a keyListener that waits for a key to be pressed and then prompts the user if he wants to close the server. However, this would only work if there was some way to check for a client every iteration of the loop, but not block. The other thing I had in mind was putting the file writing code into some place that java always runs before it closes a program.
I'm looking for someone to explain how I could either check for a client without blocking, or make some code run every time I close the program. If the above explanation was confusing, I'd be happy to clarify.

