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.
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.
subject: Synchronization of the Servlet Context Object