In a servlet container, servlet ‘S’ is instantiated and has served a few requests. It has a dependency on an object ‘O’ so it created that object when ‘S’ was instantiated. The only reference to ‘O’ is through ‘S’.
After serving the first few requets, ‘S’ did not receive any requests for a long time. Now the question is: will ‘S’ be garbage collected, and ‘O’ along with it?
Or in other words, is there some server object ‘A’ that refers to ‘S’ due to which it won’t be garbage collected no matter if it served any requests in a long time? If there’s some such object ‘A’, then who is referring to ‘A’ so ‘A’ isn’t garbage collected and so on?
There is no perfect answer to your question. Section 2.3.4 in the Servlet 3.0 specification states that:
So it highly depends on the container itself. Some may provide configuration features to unload a servlet after a certain time of inactivity (I’m not aware of any, but never had the need for a feature like that).
Conclusion
Garbage collection of the Servlet itself depends on the container and should take place after
javax.servlet.Servlet.destroy()has been called. After that servlet ‘S’ should be marked for GC – including all referenced objects ‘O’ (as long as those are not referenced somewhere else). Again, it depends on the container implementation.IMO, this is not important in reality. You should always consider that a servlet lives as long as the container does, and stopping the container generally frees all memory by stopping the JVM.