File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Servlet inheritance and performance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlet inheritance and performance" Watch "Servlet inheritance and performance" New topic

Servlet inheritance and performance

Bob Hunt

Joined: Mar 26, 2010
Posts: 5

In my app I've got a lot of servlets where I have to repeat a lot of code all the time. So I decided I would write a parent class than all my servlets would extend it.

Here is the 3 main methods from my parent class:

I override the doIt method in my children classes. My question is:
Does this approach have any performance problem? Is it slower than repeat all the code in the servlet classes?
I know the container allocates a thread (or grabs one from the pool) for a new request. So all the requests have a unique stack and a unique thread. But isn't it a problem that they all call the same methods first? (doPost and handleExceptions from the parent)
I'm always confused about this kind of situation. I don't really know how it happens. There is one method from one class which is not synchronized. A tons of requests get it (it = the same unsynchronized instance method from the same instance of a class, or the same unsynchronized static method from the same class). How does it happen in detail? How can that much request execute the same (the only one) method concurrently?

Thanks in advance.
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33106

Inheritance is not slower than repeated code. Repeated code is an anti-pattern and something you should seek to avoid. If a method is not synchronized, it doesn't matter how many callers call it at the same time.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Bob Hunt

Joined: Mar 26, 2010
Posts: 5
Thank you!

But how does it actually happen? How can that many callers call and execute it at the same time?
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13036
How can that many callers call and execute it at the same time?

Because each request is operating in its own Thread with its own request and response objects and its own thread stack of local variables.

I agree. Here's the link:
subject: Servlet inheritance and performance
jQuery in Action, 3rd edition