Design question
Hello,
I have a design question about servlets.
Many people say me that I must not use static variables in servlets but they are not able to give me a reason. The question is that I have the following servlet with a private static variable and a public static method to access it outside the servlet.
publicclass cacheServletextends HttpServlet
{
privatestatic dtoAdmin objAdmin =null;
publicstatic dtoAdmin getObjectAdmin(){return (objAdmin);}
(...)
Is this a "good" design? If not, what is the alternative "academically" correct to access "objAdmin" from external classes?
Thanks in advance.
# 1
a servlet should be "stateless". The fact is that a servlet will be invoked by multiple threads at the same time, so each thread should have its own private state. A static variable however, is shared by all states and that can cause concurrent modifications.
so I agree with "many people", do not use static variables or any attributes of any kind in a servlet.
# 2
It aren't really the static variables which can cause problems (as long as you understand the definition of 'static', e.g. concurrent modifications really shouldn't be an issue), but just instance variables. Servlet instances are shared among usersessions, so you need to think twice about declaring instance variables in servlets.
Having said that, your design looks odd to me however. Rather refractor it to an utility class or another bean.
# 3
static is an even bigger problem than instance members as it shows an intention to have something globally shared.
In case of (potentiall) distributed systems like servlets that's no longer the case (in fact in Java it's quite possible to have static being NOT globally shared even in non-distributed systems if multiple classloaders are involved).
# 5
Hello,
Thanks for your response!. Maybe I should explain with a bit more detail my problem.
The "objAdmin" is initialized just in the "init" method of servlet. This object has data from a database. Then:
1. Its information is read (and sometimes modified) by the instance threads of this servlet (any request that executes "service" method).
2. But, at the same time, is declared "static" because its content is modified by many "writters" classes outside this servlet.
3. Obviously, there is a complex synchronization system to assure that all accesses to "objAdmin" are thread safe.
That's why I declared the variable static. Otherwise it's impossible to modify it from the "writer" class.
How can I achieve this without declaring this variable static?
Too, I though to build a singleton and declare "objAdmin" inside it, and therefore forgetting the static variable.
Thanks.