Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Are static methods thread safe in a web app?  RSS feed

 
Andrei Antonescu
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I have an web app and i want to use some static methods (static getUsers() ...) to run some queries on a database. Is that ok from a thread access point of view?

Thanks in advance
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Static methods would be accessing static data and static data is shared across all the instances of that class. Shared data is never thread-safe.
From thread safety perspective it depends on how you are modifying and accessing that data. If you have only read-only operation on that shared data (e.g. getXXX) then you will not run into threading issues for the shared data. But if you have a scenario where you modify as well as read the data then you can run into reading corrupted data.

Hope that helps clarifying your doubt.

regds,
Amit
 
Sunny Bhandari
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are performing write operations then consider using proper locking mechanism...
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its not the static ness of the method that has the issue in some ways that's safer as there is no this pointer worth of trouble. but as mentioned what does you static method do .. does it access static data (it doesn't have to you could pass all you data in as parameters and return a result for instance) ...

Static data can be a problem and as pointed out if you use that you can have issues but note none static methods can just as easily use static data and shoot themselves in the foot.

One of the reasons for not using static data in a web app is scalability where does your static data live when is it instantiated what are your class loaders doing, there's a lot of really, really nasty gotchas that aren't that much to do with threading as such, singletons are fun in a clustered web application (though a lot of work has been done on this recently) for the same reasons.

In summary static getUsers is fine any of the problems caused can just as easily be created by a non static getUsers, its how you implement a static get users that may be the issue.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!