File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes Synchronization of the Servlet Context Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Synchronization of the Servlet Context Object" Watch "Synchronization of the Servlet Context Object" New topic
Author

Synchronization of the Servlet Context Object

john kerl
Greenhorn

Joined: Jul 29, 2011
Posts: 13
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.
Pankaj Kumarkk
Ranch Hand

Joined: Apr 17, 2011
Posts: 108
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.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronization of the Servlet Context Object
 
Similar Threads
Synchronization of ServletContext Object.
Duplication of Servlet Context on each JVM
Thread safe
Context Attributes are not thread safe??
why config is read only???