• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Synchronization of the Servlet Context Object

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

While going through a topic called How to make synchoronization for context objects, I came through this sentence in "Head First Servlets and Jsp's" . I am not clear on the below para because, if one thread (i.e, request) gets the lock on a context object, how can other servlets run without the context (As they cannot get the lock on it). I know we shouldn't use the context object to set attributes, which can be changed by multiple users, but the below para, raises the confusion for me. Can anybody please explain me regarding this.

You don’t need a lock on the servlet...
you need the lock on the context!
The typical way to protect the context attribute is to
synchronize ON the context object itself. If everyone
accessing the context has to first get the lock on the context
object, then you’re guaranteed that only one thread at a
time can be getting or setting the context attribute. But...
there’s still an if there. It only works if all of the other code that
manipulates the same context attributes ALSO synchronizes on the
ServletContext. If code doesn’t ask for the lock, then that code
is still free to hit the context attributes. But if you’re designing
the web app, then you can decide to make everyone ask for the
lock before accessing the attributes.
 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
All the above para means is that if you want to synchronize access to servletcontext (so that different threads can access/modify it in a sequential manner) then you need to ensure that you get the servlet context lock so that other threads(synchronized on same lock) can't access it.
Note: This is more to do with how threading works in java.
This doesn't stop any thread to access servletcontext without lock. It will just mean that your application will behave in an inconsistent manner.

 
reply
    Bookmark Topic Watch Topic
  • New Topic