Forums Register Login

Instantiation of servlet classes

+Pie Number of slices to send: Send
Hi,
how can I be sure that only one instance of a servlet class is created? I thought the web container just creates a new instance when there is no one before. In my application several servlet instances of the same class ( 5 with Weblogic, 2 with JBoss-Tomcat4.0.3) are created within the first POST-Method. But I only want one instance of this class. When exactly does a web container create new instances of a servlet class? Can I configure this behavior in the deployment descriptors?
Thanks in advance
Alex
+Pie Number of slices to send: Send
According to the servlet API, the servlet engine is supposed to create only one instance for a given web application (unless the servlet class implements the SingleThreadModel interface.)
The servlet engine is supposed to create an instance and execute the init method before any request is processed. This might be when the engine starts up or when the first request is received.
What is leading you to believe that multiple instances are being created?
Bill
+Pie Number of slices to send: Send
Hi Bill,
thanks for your response!
My Servlet actually implements the SingleThreadModel.
I'm quite sure that multiple instances are being created, because I put a control message in the servlet's init-method (System.out.println("Servlet initialised...")), as well as one in the servlet's doGet and one in the doPost method( System.out.println(this.hashcode()). While running the application I'm getting multiple messages from the init-method, when I invoke the servlet's methods for the first time. And after that I'm also getting multiple hashcodes when the servlet's methods are being used. So there is definitely more than one instance.
Is there any possibility that a servlet engine creates more than one instance of the same servlet class for just one request?
Best regards
Alex
+Pie Number of slices to send: Send
 

Originally posted by William Brogden:
According to the servlet API, the servlet engine is supposed to create only one instance for a given web application (unless the servlet class implements the SingleThreadModel interface.)


There's your answer. Were it not so, the server would be forced to block for each request, impacting performance.
If you want a singleton object, don't make it a SingleThreadModel object, but make sure you guard class-scope data in accordance with good multi-threading practices.
+Pie Number of slices to send: Send
Hi,
now I got it! Thank you both for your help!
Alex
I don't always make ads but when I do they're tiny
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 846 times.
Similar Threads
Servlet's constructor
init()
java - single thread model
when init() is being called?
Some Clarification about servlet ??
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 05:38:25.