aspose file tools*
The moose likes Servlets and the fly likes Synchronizing on the getServletContext() object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Synchronizing on the getServletContext() object" Watch "Synchronizing on the getServletContext() object" New topic
Author

Synchronizing on the getServletContext() object

Kiran Kb
Greenhorn

Joined: May 22, 2009
Posts: 6
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

Joined: Nov 06, 2000
Posts: 1510
This will ONLy protect you from all other servlets that also synchronizes on the ServletContext.

Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12806
    
    5
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

Joined: Jan 10, 2002
Posts: 61432
    
  67

"Kiran Kb", please check your private messages for an important administrative matter.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronizing on the getServletContext() object