Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronizing on the getServletContext() object

 
Kiran Kb
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

Say servlet A doGet() is having getServletContext().setAttribute("x",94);

If synchronization is not implemented, servlet B can change the value of x.

Synchronizing doGet() does not solve the problem, because it ll stop other requests for the same servlet, but other servlets can still change the value of x.

If we synchronize on the getServletContext() object, say servlet A had set x value, came out of sync block, other servlet B will enter its sync block and change the value of x.
Next time servlet A comes in, and sees that the value has been changed.
Then what is the fun in synchronizing it?

When servlet A is accessing context object, all other servlets will be blocked to access the context since there is a lock on it.
Won't that hit the hundreds of servlets which have to wait to get the context object.

Regards
Kiran
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This will ONLy protect you from all other servlets that also synchronizes on the ServletContext.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13064
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using servlet context to store a user specific value would be very bad design, comparable to using instance variables.

The Servlet API very sensibly provides objects for holding values in various scopes, from request all the way to entire servers. You just need to find the right one. Wrapping your programmer mind-set around multiuser environment takes some work if you are only used to single user desktop applications.

Bill
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64967
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Kiran Kb", please check your private messages for an important administrative matter.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic