I'm building a client-server application on Java with sockets. As far as I've understood to create a thread for every client being connected is too expensive. Instead we can use ThreadPool Executor
. As said in the concurrent documentation we can create a thread pool with a fixed size.
class NetworkService implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
public NetworkService(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
}
public void run() { // run the service
try {
for (;;) {
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
And it seems we have at most poolSize
thread running at every point of time. But what if we need to maintain a number of connection that is more than poolSize
. How is it going to work?