春季引导网络应用程序表现得就像是单线程的。

huangapple go评论60阅读模式
英文:

Spring boot web app acts like it's single-threaded

问题

以下是翻译好的部分:

我正在本地测试一个 Spring Boot 控制器,我注意到了一些令我感到惊讶的行为。我编写了这个示例控制器方法:

@GetMapping()
public void test() throws InterruptedException {
    for(int i = 0; i < 5 ; i++) {
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " " + i);
    }
}

然后我从两个不同的标签页几乎同时调用了这个端点。我原以为会从两个线程中看到日志输出重叠(因为我认为每个请求都会创建一个新的执行线程)。然而,我得到的输出是:

http-nio-8080-exec-1 0
http-nio-8080-exec-1 1
http-nio-8080-exec-1 2
http-nio-8080-exec-1 3
http-nio-8080-exec-1 4
http-nio-8080-exec-1 0
http-nio-8080-exec-1 1
http-nio-8080-exec-1 2
http-nio-8080-exec-1 3
http-nio-8080-exec-1 4

这看起来像只有一个线程,第二个请求实际上等待第一个请求完成。我原以为 Tomcat 默认的最大线程值是 200。有人可以解释一下这个行为吗?为什么没有创建多个线程?

这是一个空白项目,是使用 Spring Initializer 创建的,只有 Spring Boot Starter Web 作为依赖。

英文:

I'm testing a Spring Boot controller locally and I noticed some behaviour that surprised me. I wrote this examplary controller method :

@GetMapping()
public void test() throws InterruptedException {
    for(int i = 0; i &lt; 5 ; i++) {
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + &quot; &quot; + i);
    }
}

And I called the endpoint twice from separate tabs almost at the same time. I was expecting to see log output overlapping from two threads (as I thought that each request would create a new execution thread). Meanwhile, the output I got was:

http-nio-8080-exec-1 0
http-nio-8080-exec-1 1
http-nio-8080-exec-1 2
http-nio-8080-exec-1 3
http-nio-8080-exec-1 4
http-nio-8080-exec-1 0
http-nio-8080-exec-1 1
http-nio-8080-exec-1 2
http-nio-8080-exec-1 3
http-nio-8080-exec-1 4

This looks like there's only one thread, and the second requested actually waited for the first one to finish. I thought the tomcat default max thread value was 200. Can someone please explain this behaviour to me? Why weren't there multiple threads created?

It's a blank project, created from Spring Initializer with only Spring Boot Starter Web as a dependency

答案1

得分: 1

在Spring中,每个请求都在单独的线程中执行。例如,当两个用户同时想要登录时,JVM会创建两个线程:一个线程用于第一个用户,另一个线程用于第二个用户。

我尝试了您的情况,它完美地运行了,可能是因为您的请求不是那么并发,您可以使用 curl 命令:

curl  http://localhost:8080/hello/Logan & curl http://localhost:8080/hello/Leon
英文:

> In Spring every request is executed in separate thread. For
> example,when 2 users want to login at the same time, JVM creates 2
> threads: one thread for first user, another one for second user.

I tried your case and it works perfectly may be your requests are not that concurrent ,you can use curl

curl  http://localhost:8080/hello/Logan &amp; curl http://localhost:8080/hello/Leon

huangapple
  • 本文由 发表于 2020年9月23日 02:17:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64015531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定