1

What should be done to manually stop Servlet as calling destroy doesn't help unless all threads exited from service.

Say, If I have n number of Servlets and I want to stop only one of them.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Charu
  • 129
  • 1
  • 1
    Why do you want to do that? Depending on your end goal, it may be better to just disable the normal functionality of the servlet (i.e. convert it into a NOP) instead of disabling the servlet itself. – abl Dec 25 '14 at 15:41

1 Answers1

1

That behavior is very important when dealing with Servlets. Instances can be created after the multi-thread model and are thus not thread-safe.

The container does not allow a thread to invoke the service method after destroy has been called.

This gives you the means to close all resources that your Servlet is using (db, file, memory, etc).

@WebServlet
public class OncePerApplicationServlet extends HttpServlet {

private Connection connection;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if(req.getParameter("closeServlet").equals("true"))
        this.destroy();
    else
        this.service(req, resp); // normal flow
}

// this method will never be called by the container after the destroy method has been invoked
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1.
    try {
        connection = DriverManager.getConnection("someDbUrl");
        Statement stm = connection.createStatement();
        stm.execute("select * from someTable");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

@Override
public void destroy() {
    // the point is that when this method is called you should be able to
    // clean up and close all resources, you can rest assured that there are no "loose"
    // threads that need the connection-instance
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

Here is a quote from the API-docs:

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:

The servlet is constructed, then initialized with the init method. Any calls from clients to the service method are handled. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized. |

Link to the documentation

Good luck!

thomas77
  • 1,100
  • 13
  • 27
  • I stand corrected. They are not singletons. But, in a multi-threaded model there can be multiple instances of a Servlet created by the container. So it is up to the programmer to make the code thread-safe. In a single-threaded model, every requests is handled in sequence. – thomas77 Dec 25 '14 at 15:15
  • 1
    Servlets ARE singletons. Only one instance of a servlet can ever exist in the whole life-cycle of the webapp. That instance can be accessed my multiple threads, hence the need for thread-safe code. Excellent explanation at: [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading) – abl Dec 25 '14 at 16:10
  • So, you mean that its not possible to stop servlet manually. ASFAIK, calling destroy() in program will not help to stop servlet forcefully until it is not done with service which is correct also. To clarify more, this question has been asked in one of the interview so I am curious to know how this can be done? – Charu Dec 25 '14 at 16:36
  • @abl I actually think that your answer is wrong! A web container will typically create a thread to handle each request. To ensure that a servlet instance handles only one request at a time, a servlet can implement the SingleThreadModel interface. If a Servlet implements this interface, no two threads will execute concurrently in the Servlet’s service method. A container can implement this guarantee by synchronizing access to a single instance of the Servlet or by maintaining a pool of web component instances. This interface does not prevent synchronization problem – thomas77 Dec 25 '14 at 18:32
  • Admittedly, there are some situations in which there could be more than one instance per servlet, such as when implementing `SingleThreadModel` (deprecated since Servlet 2.4) or when the application is distributed across several VMs. – abl Dec 25 '14 at 19:03