gpt4 book ai didi

jakarta-ee - Tomcat : Multithreading and resource cleanup

转载 作者:行者123 更新时间:2023-11-28 23:03:41 25 4
gpt4 key购买 nike

在我的 Controller servlet (Tomcat) 中,我实例化了一个对象并将其分配给类的属性 (p),如下所示:

public class Controller extends HttpServlet {

String xmlFile = "/tmp/page.xml";
private Pager p = new Pager(xmlFile);

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

.............

我这样做的原因是,有很多 cpu 密集型,因此实例化完成的任务只需要完成一次(基本上它会创建应用程序的所有 html 页面结构)。

现在,我使用持久对象 (p) 并像这样访问它的一些方法:

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
.................
.................
String name = "xxxxx";
Structure str = p.doAction(name);
..................
}

我的问题是,在 Tomcat 完成该特定请求后,是否会清除由 getPageName()doAction() 等方法创建的对象、原语等?或者它将继续使用内存(与 Pager 的持久对象 p 相同)直到 Tomcat 的下一次重启/关闭?

另一个重要的问题是,由于多个请求将由 servlet 处理,它使用的对象和原语是否会有任何问题(大多数是方法本地的,但其中一些变量使用类的属性)?像这样:

public Structure doAction(String name) {
if ( pages.containsKey(name) ) {// Here pages is a property of this class (a HashMap)
return( new Structure( (Structure)pages.get(name) )); //this creates a "deep copy of this object and sends it back...
}
return( new Structure() );
}//

如上述方法所示,页面 HashMap 将采用以下形式:

page1 => its Structure Object,
page2 => its Structure Ojbect,
..... => .....................,
pageN => its Structure Object

因此,如果 Servlet 同时收到许多请求,例如:假设在特定时间 t page2N 个请求,从 doAction() 方法访问 pages HashMap 会有任何问题吗? (因为它是类的属性,所有这些 N 数量的请求将同时访问它(只读,不写入))。我的意思是,是否会有“读锁”之类的东西?

提前致谢。

最佳答案

will the objects, primitives etc created by the methods like getPageName() and doAction() be cleaned up after Tomcat has done with that particular request ?

这取决于。如果这些对象/基元被 p 直接或间接引用,那么它们将被保留用于下一个请求(术语可传递可达有时用于定义这种关系)。如果这些对象不可传递可达,它们将消失并由 GC 收集。

since multiple requests will be handled by the servlet, will there be any issues with the objects and primitives it uses (most of them are local to the method, but some of these variables use properties of the Class)<..> ?

方法本地对象(如果未在别处引用)是线程安全的,不会产生任何问题。类属性通常永远不会改变,除非您正在修改它们(无论如何这都是一个奇怪的想法)它们应该没问题。

if the Servlet receives many requests at the same time, will there be any issues accessing the pages HashMap

参见 this SO post了解更多信息。简短的回答是“如果您不修改 map 很可能没问题,但强烈建议使用专为这种情况设计的 ImmutableMap”。

关于jakarta-ee - Tomcat : Multithreading and resource cleanup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13873108/

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