• Post Reply Bookmark Topic Watch Topic
  • New Topic

why static should be avoided with web app?

 
Tapio Niemela
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I have hard time figuring out why one should avoid using static variables and methods in a web (Servlet/JSP) application with many simultoneous users (and synchronization) involved..

In http://www.sitepoint.com/forums/showthread.php?t=208975&goto=nextnewest is stated that using static in web context can lead to nasty problems. But it isn't made clear why, only something that static means there is only one and everyone shares the same one..

Let's assume that I have a servlet which inserts person into the database according to user-given parameters (like name and email)..



In this example there is a external class called DBOperations. This class has a method called insertPersonIntoDB(person p), the problem (and question) here is that couldn't it be static? So instead of method_for_inserting_person_into_DB(newPerson) in "InsertPersonIntoDBServlet" could be stated as following

DBOperations.insertPersonIntoDB(newPerson);

Wouldn't this also be thread-safe? If I remember right, local variables (and parameter values which method gets also) are thread-safe. In "InsertPersonIntoDBServlet" we could also make instance of DBOperations-class (and then call non-static insertPersonIntoDB), but is this necessary? So, what I'm basicly asking is what kind of problems might arise if static methods or variables are being used in web application? Might someone helpful person give me somekind (simple) example of problems when static is being used? Thanks..

[Edit by Dave to fix Code tags]
[ March 13, 2006: Message edited by: David O'Meara ]
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, they are referring to static variables in the servlet class:



With Servlets the container only creates a single instance, so multiple requests would use the same instance of the servlet class, and would all try to concurrently use the variables. It would (more than likely) be bad.

Dave
 
Tapio Niemela
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your reply, but I think you didn't get my point (my question was quite unclear)..

I understand that static variables should't be used with web applications, but is it true also with static methods which don't modify any static variables? e.g. static method which access only variables it self created (=local variables) and parameter-variables which came from the request-object? Request-object should be thread-safe, so shouldn't following be thread-safe?


 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That would depend on the thread safety of the method in question and nothing to do with the Servlet itself.
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each servlet creates multiple threads to handle your request. The multi-threading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, static variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can adversely affect performance and makes the code more complex.

Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure thread safety:

-- Instance pooling where container maintains a pool of servlets.
-- Sequential processing where new requests will wait while the current request is being processed.

BEST PRACTICE: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in read-only manner or shared values can be stored in a database table. The single threaded model can adversely affect performance.
 
dema rogatkin
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it mean that singleton pattern can't be applied to servlets?
 
ramprasad madathil
Ranch Hand
Posts: 489
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

BEST PRACTICE: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in read-only manner or shared values can be stored in a database table. The single threaded model can adversely affect performance.


The SingleThreadModel is deprecated in servlet 2.4
 
ramprasad madathil
Ranch Hand
Posts: 489
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tapio,

Regarding your last post, its advisable not to use it. Threads shouldnt criss-cross local variables - but I now know better. I had huge issues with it sometime back and after googling a lot, found several similar issues posted in the java forums. I dint have the time to investigate, but I remember making the methods synchronized solved the issue.

Ram.
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Imagine you got a static reference variable defined in a servlet called MyServlet like

public static HashMap hMap = new HashMap();

Then you refer to it like

HashMap map = MyServlet.hMap in another servlet called SecondServlet.

Now read what spec says

SRV.2.3.4 End of Service
The servlet container is not required to keep a servlet loaded for any particular period of time.

So always bind you objects to appropriate scope.
[ March 14, 2006: Message edited by: Vishnu Prakash ]
 
dema rogatkin
Ranch Hand
Posts: 294
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If servlet unloaded or again loaded destroy and init will be called, so static variables can be updated accordingly
 
abhinav sopory
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[/qb]<hr></blockquote>

The above code should be thread safe and will work fine.

What some of the other people are trying to say is that such code is like writing procedural programs in an OO language. Static methods cannot be overridden and hence classes with such methods are not made for polymorphism, a basic principle of OO.

But static methods are useful as convenience methods in Utility classes. Examples are methods that format strings or perform functions on numbers.

As Jousha Bloch writes in item 3 of Effective Java - "Occasionally you'll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to write procedural programs in object-oriented languages, but they do have valid uses."


So in your design it all comes down to what you think of DBOperations class. Is it a utiliy class or do you think it could get extended and you could have subclasses like (say) Db2Operations and OracleOperations. If such a thing where to happen you may be better of designing your class with non static methods. (and you would use a FactoryMethod or AbstractFactory pattern). If you think that only one istance is always used may you need to use a Singleton pattern.


In most applications that I have written the Database (access)classes (DAO) need to be instantiated (no static methods). The parent DAO class has methods that clean up resources (commit, rollback, close connections, statements etc.)(Some people may consider them as util methods but they act on data of the object so are not static) but I will still have another class usually called the DBUtil or ConnctionUtil class that will have static utility methods that are needed by the DAO classes (manage Timestamps, Dates and their formats etc.) This is a separate class and the methods are not in the parent DAO class as they provide additional utility functions best kept some place else. Also I will have a singleton (DbServiceLocator) to manage all the connection pools.

Hope this helps you decide when and where to use static methods.

Abhinav.
[ May 25, 2006: Message edited by: abhinav sopory ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!