Почему HTTPServer обрабатывает только 4 запроса одновременно?

#java #http #httpserver

#java #http #httpserver

Вопрос:

Я новичок в программировании на Java. HttpRequest может обрабатывать только <= 4 запроса одновременно, даже если newFixedThreadPool для него установлено значение 28.

  • Я пытался использовать newCachedThreadPool , но даже это обрабатывает 4 запроса одновременно.
  • Если я установил newFixedThreadPool значение 3, оно работает хорошо.
 server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newFixedThreadPool(28)); // creates a default executor
ThreadPoolExecutor t = (ThreadPoolExecutor)server.getExecutor();
LOG.info("Pool size "   t.getPoolSize()   " Max Pool size "   t.getMaximumPoolSize()   " Largest pool size "   t.getLargestPoolSize()   " Core pool size "   t.getCorePoolSize()   " actively executing threads "   t.getActiveCount()   " Completed task count "   t.getCompletedTaskCount()   " task count "   t.getTaskCount());
server.start();
  
   static class MyHandler implements HttpHandler {
      public void handle(HttpExchange t) throws IOException {
        try{
          long threadId = Thread.currentThread().getId();
          ThreadPoolExecutor t1 = (ThreadPoolExecutor)server.getExecutor();
          LOG.info("Thread #"   threadId   " before : Pool size "   t1.getPoolSize()   " Max Pool size "   t1.getMaximumPoolSize()   " Largest pool size "   t1.getLargestPoolSize()   " Core pool size "   t1.getCorePoolSize()   " actively executing threads "   t1.getActiveCount()   " Completed task count "   t1.getCompletedTaskCount()   " task count "   t1.getTaskCount());
          LOG.info("Received request on thread #"   threadId);
          String response = h.processRequest(t.getRequestURI().toString());
          t.sendResponseHeaders(200, response.length());
          OutputStream os = t.getResponseBody();
          os.write(response.getBytes());
          os.close();
          LOG.info("Request processed on thread #"   threadId);
          LOG.info("Thread #"   threadId   " after : Pool size "   t1.getPoolSize()   " Max Pool size "   t1.getMaximumPoolSize()   " Largest pool size "   t1.getLargestPoolSize()   " Core pool size "   t1.getCorePoolSize()   " actively executing threads "   t1.getActiveCount()   " Completed task count "   t1.getCompletedTaskCount()   " task count "   t1.getTaskCount());
        } catch (Exception e) {
          LOG.warn("Exception. ", e);
        }
      }
  }
  
 public String processRequest(String req)
{
   Thread.sleep(5000);
}
  

Вывод журнала

 19/04/15 16:26:07 : Thread #99 before : Pool size 21 Max Pool size 28 Largest pool size 21 Core pool size 28 actively executing threads 1 Completed task count 20 task count 21
19/04/15 16:26:07 : Received request on thread #99
19/04/15 16:26:07 : Inside Handler Sr. No [1]
19/04/15 16:26:07 : Thread #100 before : Pool size 22 Max Pool size 28 Largest pool size 22 Core pool size 28 actively executing threads 2 Completed task count 20 task count 22
19/04/15 16:26:07 : Received request on thread #100
19/04/15 16:26:07 : Inside Handler Sr. No [2]
19/04/15 16:26:08 : Thread #101 before : Pool size 23 Max Pool size 28 Largest pool size 23 Core pool size 28 actively executing threads 3 Completed task count 20 task count 23
19/04/15 16:26:08 : Received request on thread #101
19/04/15 16:26:08 : Inside Handler Sr. No [3]
19/04/15 16:26:08 : Thread #102 before : Pool size 24 Max Pool size 28 Largest pool size 24 Core pool size 28 actively executing threads 4 Completed task count 20 task count 24
19/04/15 16:26:08 : Received request on thread #102
19/04/15 16:26:08 : Inside Handler Sr. No [4]
19/04/15 16:26:12 : Request processed on thread #99
19/04/15 16:26:12 : Thread #99 after : Pool size 24 Max Pool size 28 Largest pool size 24 Core pool size 28 actively executing threads 4 Completed task count 20 task count 24
19/04/15 16:26:12 : Thread #103 before : Pool size 25 Max Pool size 28 Largest pool size 25 Core pool size 28 actively executing threads 4 Completed task count 21 task count 25
19/04/15 16:26:12 : Received request on thread #103
19/04/15 16:26:12 : Inside Handler Sr. No [5]
19/04/15 16:26:12 : Request processed on thread #100
19/04/15 16:26:12 : Thread #100 after : Pool size 25 Max Pool size 28 Largest pool size 25 Core pool size 28 actively executing threads 4 Completed task count 21 task count 25
19/04/15 16:26:12 : Thread #104 before : Pool size 26 Max Pool size 28 Largest pool size 26 Core pool size 28 actively executing threads 4 Completed task count 22 task count 26
19/04/15 16:26:12 : Received request on thread #104
19/04/15 16:26:12 : Inside Handler Sr. No [6]
19/04/15 16:26:13 : Request processed on thread #101
19/04/15 16:26:13 : Thread #101 after : Pool size 26 Max Pool size 28 Largest pool size 26 Core pool size 28 actively executing threads 4 Completed task count 22 task count 26
19/04/15 16:26:13 : Thread #105 before : Pool size 27 Max Pool size 28 Largest pool size 27 Core pool size 28 actively executing threads 4 Completed task count 23 task count 27
19/04/15 16:26:13 : Received request on thread #105
19/04/15 16:26:13 : Inside Handler Sr. No [7]
19/04/15 16:26:13 : Request processed on thread #102
19/04/15 16:26:13 : Thread #102 after : Pool size 27 Max Pool size 28 Largest pool size 27 Core pool size 28 actively executing threads 4 Completed task count 23 task count 27
19/04/15 16:26:13 : Thread #106 before : Pool size 28 Max Pool size 28 Largest pool size 28 Core pool size 28 actively executing threads 4 Completed task count 24 task count 28
19/04/15 16:26:13 : Received request on thread #106
19/04/15 16:26:13 : Inside Handler Sr. No [8]
19/04/15 16:26:17 : Request processed on thread #103
19/04/15 16:26:17 : Thread #103 after : Pool size 28 Max Pool size 28 Largest pool size 28 Core pool size 28 actively executing threads 4 Completed task count 24 task count 28
19/04/15 16:26:17 : Thread #24 before : Pool size 28 Max Pool size 28 Largest pool size 28 Core pool size 28 actively executing threads 4 Completed task count 25 task count 29
19/04/15 16:26:17 : Received request on thread #24
19/04/15 16:26:17 : Inside Handler Sr. No [9]
19/04/15 16:26:17 : Request processed on thread #104
19/04/15 16:26:17 : Thread #104 after : Pool size 28 Max Pool size 28 Largest pool size 28 Core pool size 28 actively executing threads 4 Completed task count 25 task count 29
  

Почему он обрабатывает только 4 запроса одновременно? Я делаю что-то не так?

Спасибо

Комментарии:

1. Как вы отправляете эти запросы?

2. У нас есть интерфейс, который отправляет не менее 30 запросов одновременно. processRequest функция содержит некоторую бизнес-логику, которая занимает около 5 секунд (каждый запрос).

3. Так что это не настоящий код. Итак, ваш вопрос пока бессмыслен. Очевидно, что в отсутствующем коде есть что-то, что вызывает это ограничение. Здесь ничего.

4. Это реальный код, который я протестировал (со сном) и распечатал журналы. Бизнес-логика, о которой я упоминал, была прокомментирована при выполнении.

5. Я предполагаю, что вы используете com.sun.net.httpserver.HttpServer . Документация ( docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/com /… ) утверждает: backlog - the socket backlog. If this value is less than or equal to zero, then a system default value is used. This represents the maximum number of incoming TCP connections which the system will queue internally. Итак, ваше системное значение по умолчанию равно 4. Если вам нужно больше подключений, вы должны специально установить параметр в HttpServer.create(new InetSocketAddress(port), <backlog>);