Servlets: Life Cycle
Notes available courtesy of Joel Budgor

Objectives

What are the stages in the life cycle of a servlet?

  1. Loading / instantiating the servlet.
  2. Invoking the servlet's init method.
  3. Invoking the servlet's service method.
  4. Invoking the servlet's destroy method.

How do class loaders affect the behavior of the server?

A closer look at the init method.

What does an init method look like?

What does the service method do?

Are servlets thread-safe?

What can be done to optimize the performance of a thread-safe servlet?

  1. Limit the scope of synchronization.

    Get in and out of the data as quickly as possible.

    Do not do real-time IO within synchronized code blocks.

  2. Implement SingleThreadModel interface. (How to do this? ... extends HttpServlet implements SingleThreadModel)

    What does this interface do?

    What are the benefits of this technique?

    What are the costs of this technique?

    When might you use SingleThreadModel?

    A closer look at the destroy method. The destroy method should undo any initialization work and synchronize persistent data with the current in-memory state of the servlet.

    What does a typical destroy method do?

    Servlet Reloading

    As we saw, as a server runs, its servlet engine loads the servlets that users request from disk into internal memory. Then, if there's another request for one of the servlets that's already in memory, the server doesn't reload the servlet from disk to memory. It uses the one that's in memory.

    But what if you change one of the servlets that's in memory? Rather than restarting the server each time, we would like to have servlet reloading.

    To get servlet reloading you need to set it for the server.
    Example: Tomcat
    When this option is on, Tomcat checks to make sure the requested servlet in memory is the same as the one on disk. Then, if the one on disk has been modified, it reloads the servlet before it runs it. This means that you don't have to stop and restart Tomcat each time you change a servlet.

    To turn servlet reloading on, you add a line of code to the context.xml (or server.xml?) file that's stored in Tomcat's conf directory. This XML file controls how Tomcat is configured. Here are some notes from the Murach book to show how this is done.
    Hmmm, interesting. Murach says to put it in the install_dir/conf/server.xml but Hall says in the install_dir/conf/context.xml
    I suppose since the server looks at both it might not matter, but since context.xml actually has it listed there, I would probably use that one.

    A Class Exercise

    Handout

    For more on the life cycle, see section 2.6 of Hall's book.
    Or the J2EE servlet tutorial life cycle section - interesting use of Listeners to see what is happening