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
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): <Port>");
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();
}
}
I'm not sure what you use to receive those connections, but usually frameworks that handle TCP connections non-blocking like Netty use a master thread to listen to the port and a thread pool to handle incomming connections. This means it will at least open 2 threads for the incomming connection if the thread-pool is limited to 1 thread.
See this example from the netty page, where 2 NioEventLoopGroups are used while bootstrapping the server.
The 2 threads are necessary to not block incoming traffic.