gpt4 book ai didi

java - Tomcat 执行服务已同步

转载 作者:行者123 更新时间:2023-11-28 22:26:20 25 4
gpt4 key购买 nike

看来我是崩溃了。我在 Java 9(8 相同)上使用 Tomcat 9(8 相同)创建了新项目。它只有一个 servlet

@WebServlet(urlPatterns = "/*")
public class Servlet extends HttpServlet {

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(new Date().getTime() /1000 + " " + Thread.currentThread().getName() + " Start");
/*long i = 0;

while (i < 3000000000L) {
if (i % 2 == 0) {
i++;
} else {
i++;
}
}*/
try {
Thread.sleep(2000);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(new Date().getTime()/1000 + " " + Thread.currentThread().getName() + " Done");
}
}

我的所有经验告诉我,该方法是异步工作的,但我通过浏览器中的 3 个选项卡调用 servlet(尽可能同时),我的日志中有这张图片:

1492723549 http-nio-9999-exec-2 Start
1492723551 http-nio-9999-exec-2 Done
1492723551 http-nio-9999-exec-1 Start
1492723553 http-nio-9999-exec-1 Done
1492723553 http-nio-9999-exec-3 Start
1492723555 http-nio-9999-exec-3 Done

可以看出,每个请求都会锁定方法,直到它完成。有人能告诉我为什么吗?我真的希望同时启动 3 个,并在 2 秒后完成 3 个。

谢谢!

最佳答案

根据 servlet specification :

For a servlet not hosted in a distributed environment (the default),the servlet container must use only one instance per servletdeclaration. However, for a servlet implementing theSingleThreadModel interface, the servlet container may instantiatemultiple instances to handle a heavy request load and serializerequests to a particular instance.

In the case where a servlet was deployed as part of an applicationmarked in the deployment descriptor as distributable, a container mayhave only one instance per servlet declaration per Java VirtualMachine (JVM). However, if the servlet in a distributable applicationimplements the SingleThreadModel interface, the container mayinstantiate multiple instances of that servlet in each JVM of thecontainer.

此外,here你可以找到一些关于 tomcat 的信息:

A web server such as Tomcat can instantiate arbitrarily many instancesof a servlet, although the number is typically small (e.g., 1 through4). The web server itself makes the decision.

因此,您的应用程序中只有一个 servlet 实例是绝对正常的。

请确保您确实需要重写 HttpServlet.service() 方法,因为正如 javadoc 中所述:

There's no need to override this method

关于java - Tomcat 执行服务已同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com