The order in which the destroy () method is called for servlets / filters

I have a Java web application.

I can specify the order in which the init() method is called on servlets with a parameter in web.xml :

 <load-on-startup>1</load-on-startup> 

But how can I specify the order in which destroy() methods are called?

Actually, I just need to close log4j at the end. But in advance I want to know if there are any rules for calling the destroy() method.

+6
source share
1 answer

I looked at the Servlet 3.0 specification. It does not define any rules for the order in which destroy methods should be called. Therefore, it is not listed, and you should not rely on any behavior of a particular provider. The second reason not to release resources shared in Servlets is that this servlet can be destroyed at any time - if the container decides to do so. See Section 2.3.4 of the Servlet 3.0 specification:

2.3.4 End of service

A servlet container is not required to save a loaded servlet for any specific time period. A servlet instance can be active in the servlet container for a period in milliseconds, for the life of the servlet container (which can be the number of days, months, or years) or any period of time between them.

When the servlet container determines that the servlet should be removed from the service, it calls the destroy method of the Servlet interface to allow the servlet to free any resources it uses and maintain any permanent state. For example, a container can do this when it wants to conserve memory resources, or when it shuts down

Let's say you have 3 servlets - A, B and C. If A and B rely on resources controlled by C, it may happen that the container decides to temporarily disable C by calling its destroy method. Thus, A and B will no longer have access to these resources. I must admit, I have never seen such behavior in reality.

Recommendation:

Use ServletContextListener . It is guaranteed to be initialized and destroyed only once.

+8
source

Source: https://habr.com/ru/post/893871/


All Articles