Servlet life : when is it safe to use class var's in servlet
Joined: Dec 26, 2008
I am new to servlets. i will make this brief (don't want to bore you with all of my studying process and stuff)
Granted the following class:
To my understanding at startup/(first http req) the following servlet will be initialized, and there for all its class variables alive as long as the servlet isnt destroyed, but until WHEN exactly can i trust a servlet isnt destroyed. meaning when will the count variable be 0 again (in the code abpve)?
if the answer is its up to the container to decide and we cant know (meaning arbitrary). then what are class variables in servlets useful for ?
Joined: Oct 08, 2006
You can use instance variables in servlets whenever you want to share a variable among all requests on the servlet. For example an instance of the DAO class or so which you assigned during init().
It's indeed up to the web container when a servlet will be destroyed. Normally this will happen during shutdown, but it can also be destroyed when it isn't been used for a relatively long time. That depends on the appserver implementation used. [ December 26, 2008: Message edited by: Bauke Scholtz ]
In other words, read-write class variables are fairly useless in a servlet. They can't be used for anything that isn't supposed to be shared across all threads, and for stuff that should be shared, well, they're not good for that either as there could be more than one instance loaded (based on how the web.xml is configured) or could be reloaded based upon container-dependent decisions.
Use application context or session context to store shared information.