I was reading through the KnockKnock server example at http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html and I found a bit of code I have a few questions about.
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
while (listening) {
new KKMultiServerThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + portNumber);
System.exit(-1);
}
My questions:
- What is the scope of
serverSocket
? Is it usable in the caught exception block, or elsewhere in the surrounding block? If not, how can one reliably close the socket? - How is the socket closed in this instance? I assume the only way that this sample can stop executing is to forcefully end the process, but what happens to the open socket after this point? Is the port in use no longer available for other applications (or even the same application)?
- What happens to the
new KKMultiServerThread
? Is this thread cleaned up by the garbage collector once the thread has completed its work?