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.