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.
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
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:
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.