Reputation: 1323
I am building a servlet (e.g. MainServlet) where, in order to be thread-safe, I am creating an object (e.g. MainServletProcesor) and then delegating the call to the object to process the HttpRequest. The MainServletProcessorhas instance members that are used to fulfill the request. I was wondering if this approach is fine from a performance point of view. Is this approach of creating a Processor instance per request a good idea?
Upvotes: 0
Views: 45
Reputation: 279890
Your Servlet doXYZ()
methods are entry points (your point of view) for your application. If you were to write all the logic for request handling in each of those methods, your code would very quickly become unmanageable.
What you are doing is completely reasonable and actually good practice. Creating an object takes almost no time at all. When your Servlet container receives the actual HTTP request, it actually goes and creates a ton of objects (HttpServletRequest
, HttpServletResponse
, Streams
, Headers
, etc.) without you seeing it.
You can have a look at the request processing flow for Tomcat here. This won't show you what objects are created for each request, but you can extrapolate (or look at the source code).
Upvotes: 1
Reputation: 691645
Why wouldn't it? Creating an object is cheap, and during the processing and rendering of your request, you probably create a lot more of them.
Creating an object is several orders of magnitude faster than querying a database, or writing the response to the output stream.
Upvotes: 1