I’ve written the following code to implement a Threaded Server:
ServerSocket passiveSocket = new ServerSocket(port, maxConnections);
while(true){
final Socket socket = passiveSocket.accept();
new Thread(new Runnable() {
public void run() {
//access socket as needed to communicate. E.g.:
PrintWriter writer = new PrintWriter(socket.getOutputStream());
//Finally close socket.
socket.close();
}
}).start();
}
Now this seems to work, but in reflection I do not really understand what’s going on with the final socket variable socket when the next connection arrives. How is each thread associated with the socket instance which was current when starting the thread? – is the final keyword responsible for that?
Think of it this way:
socketis secretly passed as an argument to thenew Runnableconstructor, and it’s kept as a variable in the anonymousRunnableclass. (That’s actually how it works, at the bytecode level.)The created
Runnableobject contains a reference to the one specificSocketvalue at its creation time, so it can close that specific socket when it’s done.