Daemon Threads, thread count, and total started thread count

前端 未结 2 1656
攒了一身酷
攒了一身酷 2021-02-20 17:18

I have a simple code for a multi-threaded echo server in Java (it returns whatever received back to the clients). I\'m profiling various resources of the server including the th

2条回答
  •  臣服心动
    2021-02-20 18:05

    I just hope you reviewed the Thread names in VisualVM profiler. Usually the thread names give you some idea of what is started.

    ad 1) this could very well be some TCP/IP background (cleaner, poller) thread that gets spawned as soon as you have some TCP/IP connection from outside.

    What does happen when clients go back to 0. Does extra thread disappear?

    Answers may very well differ based on JVM vendor and version. So I think you need to look in JVM internals about sockets and threads.

    Example below is more straight forward (without RMI)

    import java.net.*; // for Socket, ServerSocket, and InetAddress
    import java.io.*; // for IOException and Input/0utputStream
    
    public class TCPEchoServer {
    
        private static final int BUFSIZE = 32; // Size of receive buffer
        public static void main(String[] args) throws lOException {
            if (args.length != i) // Test for correct # of args
                throw new lllegalArgumentException("Parameter(s): ");
            int servPort = Integer.parselnt(args[0]);
            // Create a server socket to accept client connection requests
            ServerSocket servSock = new ServerSocket(servPort);
            int recvMsgSize; // Size of received message
            byte[] byteBuffer = new byte[BUFSlZE]; // Receive buffer 
    
        }
    
        for (;;) { // Run forever, accepting and servicing connections
            Socket clntSock = servSock.accept(); // Get client connection
            System.out.println("Handling client at " +
                clntSock.getInetAddress().getHostAddress() + " on port " +
                clntSock, getPort());
            InputStream in = clntSock, getlnputStream();
            OutputStream out = clntSock.getOutputStream();
            // Receive until client closes connection, indicated by-i return
            while ((recvMsgSize = in .read(byteBuffer)) != -I)
                out.write(byteBuffer, O, recvMsgSize);
            clntSock, close();
        }
    }
    

提交回复
热议问题