Web tier: servlets, JSP, Web frameworks: static variables in web tier.

  1. static variables in web tier. (2 messages)

    I am code reviewing web app, it has all the variables declared to be static , author claims making every variable static reduces the burden of creating variables for multiple instances of the servlet(not singlethreaded). Is this a good design?

    Threaded Messages (2)

  2. Recipe for disaster[ Go to top ]

    I would tend to think that is a recipe for disaster, unless of course I'm missing something.

    In general using static variables should be reserved to things that are initialized once and only read or "used" thereafter (e.g. Logger, Configuration...), everything else should be kep as much as possible as parameter and method variables. As we move more and more into the paradigm of parallel computing it is very likely that a given instance of an object is used by multiple thread (which is the case for servlet already), making all object-level variable subject to concurrency issues or cross-thread issues.

    Making variables static is even worse as it means even two instance of the same class share the reference. Which is definitely an issue for data related with the request being processed.

    My usual advice is to allow static variables only for a (very) limited set of things, and avoid static variables or class-level variables for the rest. It might seem convenient to use a class variable to attach a piece of information that is used by many methods, but as soon as this class is used as a singleton in a multi-threaded solution is breaks. Avoiding those is simply a way to make the code more future proof (and not that hard to do).

    If someone claims it means creating a lot of data each time, I would strongly suggest to look into caching strategies or review the approach more in depth.

    Hope it'll help,


  3. Recipe for disaster[ Go to top ]

    All the data they declare is read only, for instance error messages etc,  but my major concern is declaring so many variables static would hinder the garbage collection. what is the trade off between garbage collection vs over head of creating these for every instance. They have general phylosophy  is make all the string as static..  Is this a good design strategy?