On Mon, 20 Aug 2001, Miles Daffin wrote:

> This is an interesting one.
> 
> I had assumed that statics were a nono in webapps
> because they broke Context encapsulation.
> 
> It appears, however, that you can have your cake
> and eat it. At least in TC 3.2.1.
> 

Actually, in all containers that support servlet 2.2 or greater.  But you
do have to be slightly careful in one case.

Many containers (including Tomcat) let you put JAR files into a common
directory (for Tomcat, it's "lib") that are available to *all*
webapps.  Because this is outside the language of the spec, behavior
differs somewhat -- but in most cases, statics declared by a class loaded
from this global directory *are* global to all webapps.

If you want your webapps to be truly independent, then make sure that you
load all your classes from /WEB-INF/classes or /WEB-INF/lib.

> I declared a public static String in a Base servlet
> and built the host webapp twice, with two different
> values in this String into 2 war files with different
> names. After starting TC I could see that the same
> static String had different values in the 2 Contexts.
> 
> I have just reread the 2.2 spec and do not recall seeing
> anything that suggested that compliant containers must
> behave like this. Did I miss something?
> 

It's slightly indirect, but it's there.

Basically, a container is required to load all components of a web
application with a single class loader, and to use a different class
loader for each web app.  Now, if you go back to the Java Language
Specification, you'll find that the scope of a static is the class loader
it was loaded from.

Stand-alone Java applications tend not to notice any difference, because
they tend to be executed in a single class loader that was initialized
from the CLASSPATH environment variable.  In that scenario, statics are
truly global to the entire app.

> Given that it seems one can safely use statics in webapps,
> is there anything now to be said against this?
> 

Just the usual cautions about variables that can be updated from anywhere,
which can make debugging more interesting.

> 
> Miles Daffin
> 

Craig McClanahan

Reply via email to