繁体   English   中英

是否可以执行比线程池中的线程更多的请求?

[英]Is it possible to execute more requests than there are threads in thread pool?

我使用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线程称为软线程,与处理器核心/线程号无关。

通常,HTTP Server以及Servlets / App容器都与线程池一起使用,这意味着一旦达到线程池上限,其余请求将保持阻塞状态。 那是阻止方法。

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

当然,您可以同时产生三个以上的线程,并获得Future结果。

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

ForkJoinPool myPool = new ForkJoinPool(100); // number of tasks executed in parallel

CompletableFuture.supplyAsync(..., myPool);

对于网络请求,拥有比CPU内核更多的线程是很正常的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM