Reputation: 129
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.
Upvotes: 1
Views: 892
Reputation: 1150
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. |
Good luck!
Upvotes: 1