In below there is question and answer, What I need is I want comment about the a
ID: 3592553 • Letter: I
Question
In below there is question and answer, What I need is I want comment about the answer( feel free to agree or disagree with answer) in few paragraph
Question:
Why is it a good idea to do the database initialization in the init() method rather than the doGet() or doPost()? Discuss.
Answer:
It is generally good practice to do initialization inside of the init() method. The init() method is only called once when the servlet is created whereas the deGet() and doPost() methods are called every time the user presses a button. You don’t want to constantly be reinitializing the database every time the doGet() or doPost() methods are called. This would add overhead to the application.
Explanation / Answer
Hi,
I absolutely agree with your answer that DB shouldn't be initialized in doGet()/doPost() methods. And the reason you have mentioned is also correct for not using doPost() and doGet() because that would definitely add overhead to the application. If there is a connection object for every request, and there are too many client requests, then ultimately several connection objects would be using up the memory at the same time, and memory might become unavailable for any further requests and the application might ultimately crash down!
But, it is also not advisable to initialize DB in init(), and the following approcah should be followed:
Use Database Connection pooling, instead of initializing a new DB connection in init().
1.If you open a connection in init(), and it isn't used for long, the connection would time out, and the only way you'll have, is to reload the servlet for the DB connection to work. Whenever a database connection is requested by our servlet, this connection pool would either return an open connection or create a new one and return it.
2. Database connection pooling would also resolve concurreny issues that might come up when multiple instances of servlet are running for each of the client's requests.
It's even a better practice to do it in a separate ContextListener rather than in init(). Let me know if you want to know more about it.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.