An attempt to use resources in a multithreaded server in Java
•
Java
I'm reading a book "java networking 4th Edition" and Chapter 9 on server sockets, while explaining the multi-threaded server, in which each client uses a single thread for processing. It says as follows:
This is example 9-3
import java.net.*; import java.io.*; import java.util.Date; public class MultithreadedDaytimeServer { public final static int PORT = 13; public static void main(String[] args) { try (ServerSocket server = new ServerSocket(PORT)) { while (true) { try { Socket connection = server.accept(); Thread task = new DaytimeThread(connection); task.start(); } catch (IOException ex) {} } } catch (IOException ex) { System.err.println("Couldn't start server"); } } private static class DaytimeThread extends Thread { private Socket connection; DaytimeThread(Socket connection) { this.connection = connection; } @Override public void run() { try { Writer out = new OutputStreamWriter(connection.getOutputStream()); Date Now = new Date(); out.write(Now.toString() +"\r\n"); out.flush(); } catch (IOException ex) { System.err.println(ex); } finally { try { connection.close(); } catch (IOException e) { // ignore; } } } }
}
I really don't understand why this happens. Why does the main thread close the socket from another thread because the socket object is created in the main thread and the reference is provided in the thread constructor?
Solution
What this book means is that they choose to do so
try { Socket connection = server.accept(); Thread task = new DaytimeThread(connection); task.start(); } catch (IOException ex) {}
replace
try(Socket connection = server.accept()) { Thread task = new DaytimeThread(connection); task.start(); } catch (IOException ex) {}
Because when you use the try with resources block, it closes anything you put in the brackets try (...) as soon as it's done But you don't want this to happen The socket is connected to remain open because it will be used in the launched daytimethread
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码