ThreadPool executor and huge number of clients connected at the same time

I am creating a Java client server application with sockets. As far as I understood, it is too expensive to create a thread for each connected client. We can use instead ThreadPool Executor

. As the parallel documentation says , we can create a fixed size thread pool.

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 that we have, in most cases, a thread poolSize

executing at every point in time. But what if we need to support multiple connections that are larger than poolSize

. How will it work?

+3


source to share


1 answer


If you do have a huge number of clients, you should consider NIO , because creating a stream for each client would be too costly.

NIO uses selectors and channels and does not require a new stream to be created for each connection. See image .



Have you heard of netty ? I don't know what you are going to implement, but it looks like it will be helpful.

+3


source







All Articles