Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization of the Servlet Context Object  RSS feed

john kerl
Posts: 13
  • Mark post as helpful
  • send pies
  • 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.
Pankaj Kumarkk
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!