permaculture playing cards*
The moose likes Servlets and the fly likes Servlet instance is started twice Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlet instance is started twice" Watch "Servlet instance is started twice" New topic
Author

Servlet instance is started twice

Mateusz Moroz
Greenhorn

Joined: Oct 29, 2008
Posts: 21
Hi,

I got a problem with my servlet on OC4J, because it instance is being created twice by the container. My web.xml:



and my servlet code:



1. The init() method is called twice
2. The destroy() method isn't called
3. The servlet is mapped only once
4. Each time servlet starts, the instances attribute is 0 and the previously created singleton JournallingOrdersGenerator is null

The problem is, that when servlet starts twice, the singleton object JournallingOrdersGenerator is again null and is created (and started) twice.

I'm desperated and I have no more ideas how to fix it. Do you know any solution? I've read that on Tomcat is the same problem.

Regards
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Sure. Just don't use an instance variable in a servlet for an object which needs to be a singleton in your application's scope.

Instead create a class which implements ServletContextListener. When it is initialized:

Then anywhere you have access to the servlet context (e.g. in any servlet), you can get that attribute from it and use it.

You'll need to mention that class in your web.xml like this:
Mateusz Moroz
Greenhorn

Joined: Oct 29, 2008
Posts: 21
GREAT! Even the servlet is now being created once, what I don't understand (but its way it should!)
Thanks Paul
[ November 06, 2008: Message edited by: Mateusz Moroz ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Servlet instance is started twice
 
Similar Threads
servlet mapping clarification
Problem Migrating a Project from Weblogic 9.2 to Tomcat 6.0.29
Using a filter with frontman
HttpSessionListener is not getting invoked
HTTP Status 404 - Servlet Not Found