Because anyway, only one instance of servlet exist at any time, so what difference it makes to declaring static variable and instance variable....
Is this a better description?
[ December 06, 2005: Message edited by: David O'Meara ]
Originally posted by Bear Bibeault:
And of course by introducing either static or instance variables you are likely to create threading issues since the single instance of the servlet is shared amongst all threads processing requests. Tread carefully.
Exactly. Since the usual idiom is for each thread to have its own set objects, declaring variables static in a Servlet makes future programmers think, "Hmmm... I better tread carefully because these variables are shared between Threads."
(Not modifying what David and Bear have said, just emphasizing.)
If you don't believe me, put something like this in your web.xml and verify it yourself!
In containers like Tomcat, each webapp has it's own classloader for it's servlets. This means static variables declared in classes within one app will be isolated from other apps running in the same container.
Occasionally, developers/sysadmins will want to have several apps to share common libraries and may be tempted to put jar files in a common area. In Tomcat this would either be tomcat/common/lib or tomcat/shared/lib. In this case, static variables would be shared across webapps; something you may not have intended.
With hard disk space being so cheap and with so many good build tools like ANT out there, I think it is folly not to pack each app with all the needed libraries; even if this means that the same jar file exists in a dozen places on one server. Nevertheless, there will always be those who will try this. If you see yourself or your sysadmin going down this road, it's a good idea to know if you're using static variables in your servlets.
But please do make sure you consult your container documentation to understand how the change detection and propagation takes place.