Java Servlet 池
Servlets 101, under Tomcat 6:
有人可以给我指出一个关于最佳方法的很好的解释吗?在 servlet 启动时创建一个昂贵的 Foo 对象的集合,并将它们存储在我可以在处理每个请求时访问它们的地方?
据我所知,至少有三种方法可以做到这一点,但我对其中的区别有点模糊。我不关心集群或算法来驱逐过时的条目或类似的东西,只是基础知识。
干杯和感谢。
Servlets 101, under Tomcat 6:
Could someone kindly point me to a good explanation of the best way to eg. create a Collection of expensive Foo objects at servlet startup time and stash them somewhere where I can access them while processing each request?
Near as I can tell there are at least three ways to do this and I am a bit fuzzy on the difference. I am not concerned with clustering or algorithms to evict stale entries or anything like that, just the basics.
Cheers and Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实现
ServletContextListener
,在contextInitialized()
期间执行所需的加载任务,并通过ServletContext#setAttribute()
将结果存储在应用程序范围中。它将在服务器启动期间被调用,并且应用程序范围也可以在常规 servlet 内访问。基本示例:
以通常的方式在
web.xml
中映射它:以下是如何在常规 servlet 中访问它:
以下是如何在 JSP 中访问它:
也就是说,我真的不明白如何做到这一点与“servlet 池”相关。这个词没有任何意义。
希望这有帮助。
Implement a
ServletContextListener
, do the desired loading task duringcontextInitialized()
and store the result in the application scope byServletContext#setAttribute()
. It will be invoked during server's startup and the application scope is accessible inside regular servlets as well.Basic example:
Map it in
web.xml
the usual way:Here's how to access it in regular servlets:
And here's how you can access it in JSPs:
That said, I really don't see how that is related to "servlet pool". This term makes no sense.
Hope this helps.
您有多种选择:
You have several options:
您正在寻找对象池。通常,对象池是使用空闲对象列表构建的,当释放资源但未达到空闲对象的最大数量时,将其添加到列表中。
我不会预先填充池,只需在空闲对象池为空时分配一个新对象。
一个显着的性能优势是为最后释放的对象保留 1 个引用。不必将其添加到空闲对象列表中,对于交替分配和释放 1 个对象的情况可以节省很多。如果引用不为
null
,则将下一个释放的对象添加到列表中,分配时返回最后一个释放的对象,并将其null
。You are looking for an object pool. Typically an object pool is built using a list of free objects, adding to the list when resources are freed while the maximum amount of free objects is not reached.
I would not fill the pool upfront, just allocate a new object if the pool of free objects is empty.
One notable performance win is to keep 1 reference for the last freed object. Not having to add it to the list of free objects saves a lot for situations where 1 object is allocated and freed alternatively. If the reference is not
null
add the next freed object to the list, on allocation return the last freed andnull
it.您可以使用 servlet 上下文。
servlet 上下文对于所有 servlet 实例都是通用的,并且其生命周期超出了请求和会话。
您可以在那里放置任何内容,例如:
这是一个链接,您可以在其中阅读更多内容 关于它
You can use the servlet context.
The servlet context is common to all servlets instances and its life cycle goes beyond the request and session.
You can put anything there like:
Here's a link where you can read more about it