【问题标题】:Is it possible to execute more requests than there are threads in thread pool?是否可以执行比线程池中的线程更多的请求?
【发布时间】:2015-09-16 06:01:24
【问题描述】:

我使用 Java 和 Spring 开发 Web 应用程序。为了检查当多个请求到来时系统的行为,我创建了测试:

@Test
public void shouldHandleMultipleRequests() throws Exception {
    //given
    final String endpoint = "http://localhost:9000/upload";
    final File file = new File(format("src/test/resources/files/%s", 
        "file.txt"));  
    //when
    final CompletableFuture<String> response1 = CompletableFuture.supplyAsync(() -> 
        Try.ofFailable(() -> 
        HttpClientBuilder.create().build().execute(
        createHttpPost(endpoint, file))).orElse(null).getEntity().toString());
    final CompletableFuture<String> response2 = CompletableFuture.supplyAsync(() -> 
        Try.ofFailable(() -> 
        HttpClientBuilder.create().build().execute(
        createHttpPost(endpoint,file))).orElse(null).getEntity().toString());  
    assertThat(response1.get().contains("Something")); 
    assertThat(response2.get().contains("Something"));

}

一切正常,但是我注意到,如果我尝试运行 3 个以上的请求,则前 3 个请求和下一个请求之间会有延迟。

我的问题是

  • 我认为这种行为是否与我的处理器上的线程数有关(4 个线程处理器,3 个用于请求和等待响应的线程,以及一个用于应用程序)?
  • 如果有任何方法可以同时发送 3 个以上的请求(当然是稍后检索响应)?

【问题讨论】:

    标签: java multithreading spring testing integration-testing


    【解决方案1】:

    CompletableFuture.supplyAsync 使用常见的ForkJoinPool 提交任务,默认情况下线程数受Runtime.getRuntime().availableProcessors() 返回的硬件线程数限制。但是,您可以使用两个参数 supplyAsync 创建自己的池并将其用于您的任务:

    ForkJoinPool myPool = new ForkJoinPool(100); // number of tasks executed in parallel
    
    CompletableFuture.supplyAsync(..., myPool);
    

    对于网络请求,线程数多于 CPU 内核数是很正常的。

    【讨论】:

      【解决方案2】:

      Java 线程是所谓的软线程,与处理器内核/线程数无关。

      通常,HTTP 服务器和 Servlets/App 容器与线程池一起工作,这意味着一旦达到线程池上限,其余请求仍然被阻止。这就是阻塞方法。

      但是,还有另一个选项可以配置非阻塞连接器。阅读此Tomcat Connectors Document,您可以获得更深入的知识。因此,如您所见,您可以调整服务器行为,因为这是连接器配置的问题。

      当然,您可以同时生成三个以上的线程并接收Future 结果。

      【讨论】:

        猜你喜欢
        • 2014-12-02
        • 2013-06-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 1970-01-01
        • 2021-06-16
        • 2012-06-16
        • 1970-01-01
        相关资源
        最近更新 更多