Bug 48088

Summary: Servlet implementing SingleThreadModel are initialized twice
Product: Tomcat 5 Reporter: Anthony Goubard <anthony.goubard>
Component: CatalinaAssignee: Tomcat Developers Mailing List <dev>
Status: RESOLVED WORKSFORME    
Severity: normal    
Priority: P2    
Version: 5.5.28   
Target Milestone: ---   
Hardware: PC   
OS: All   

Description Anthony Goubard 2009-10-30 03:28:03 UTC
When a Servlet implements javax.servlet.SingleThreadModel the method init is called twice. This should not happen according to the Servlet specification.

http://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#lifeCycle

I first saw the bug when someone tried when someone submitted a bug in my open source web services framework "xins"
http://sourceforge.net/tracker/?func=detail&aid=2884574&group_id=71598&atid=531814 (bug submitted from Linux with Tomcat 5.5.25)

Here the petstore demo is initialized at the start-up of Tomcat and with the first request http://localhost:8080/petstore/. This apparently happens on the same Servlet object.
I've attached the war file that contains removed code so that the Servlet initializes correctly the first time without looking for a database.
Source code and Demo available at http://xins.sourceforge.net/

I've tried to reproduce it (See code below) and had a slightly different behaviour:
The init method is called twice but at the first request and it seems to be done on 2 different objects as the exception is not thrown. The destroy method is also called twice at the end.

public class SimpleServlet extends HttpServlet implements javax.servlet.SingleThreadModel {

    private boolean initialized = false;
    private int initCount = 0;

    public void init(ServletConfig config)
        throws IllegalArgumentException, ServletException {
        if (initialized) {
            throw new ServletException("Servlet already initialized. Should not happen according to the specs.");
        }
        initialized = true;
        System.err.println("------------ Initialized -");
        initCount++;
    }


    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        out.println("SimpleServlet Executed " + initCount);
        out.flush();
        out.close();
    }

    public void destroy() {
        initialized = false;
        System.err.println("------------ destroy");
    }
}
Comment 1 Mark Thomas 2009-11-06 13:39:44 UTC
When a servlet implements javax.servlet.SingleThreadModel multiple instances of the Servlet will be created to provide a pool of Servlet objects. This looks like what you are seeing.

If this does not explain what you are seeing, please re-open and attach a test case that demonstrates the problem.