๐ฆ๐ฒ๐ฟ๐๐น๐ฒ๐ ๐๐ถ๐ณ๐ฒ๐ฐ๐๐ฐ๐น๐ฒ ๐๐ ๐ฝ๐น๐ฎ๐ถ๐ป๐ฒ๐ฑ
Java web applications handle thousands of requests every day. A servlet acts as the bridge between the user and your backend logic.
If you do not understand the servlet lifecycle, you risk memory leaks and slow performance.
The servlet container, like Apache Tomcat, manages three main stages:
- Initialization (init)
- Request Processing (service)
- Destruction (destroy)
Here is how it works:
Phase 1: Initialization The container loads the servlet class and creates one instance. The init() method runs only once. Use this stage to set up database connections or load configuration files. Doing this once prevents the server from reconnecting on every request.
Phase 2: Request Processing The service() method runs for every incoming request. It identifies the request type, such as GET or POST. It then sends the request to methods like doGet() or doPost(). Note: The container uses one servlet instance to handle many requests using different threads. Do not store request-specific data in instance variables. This prevents data conflicts between users. Always use local variables to ensure thread safety.
Phase 3: Destruction The destroy() method runs only once when the server shuts down. Use this to close database connections and release resources. Proper cleanup prevents memory leaks.
Why this matters: Even if you use Spring Boot, you are still using a servlet container. Spring MVC relies on the DispatcherServlet to manage requests. Knowing these fundamentals helps you debug production issues and build scalable systems.
Summary for interviews:
- init(): Runs once at startup.
- service(): Runs for every request.
- destroy(): Runs once at shutdown.
- Container: Manages the whole process.
- Threads: Multiple users share one servlet instance.
Source: https://dev.to/naveenkumar1/servlet-lifecycle-explained-with-practical-examples-41p