• Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding synchronization on ServletContext attributes

 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Referring to: book 'Head First Servlets & JSP', 2nd edition, page 197

Context attributes can be protected from concurrent access only if each part of the web application accessing them asks for a lock on the context.

See here:
book wrote:
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.



I am confused about that last sentence; I seem to be misunderstanding the use of the keyword 'synchronized'.
I don't understand how it is possible for another part of the web application (threads) to change a ServletContext attribute that has been locked:



If it has been synchronized (locked?), then how is it possible for another part of the application to modify it?

 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It has been locked only for that piece of code - so that code will have to wait if some other piece of code has gotten hold of the ServletContext object as a lock.

What that excerpt talks about is that nothing stops some other piece of code -somewhere in that possibly humongous pile of web app code maintained by multiple developers- to access those attributes without synchronizing on anything - and hence nothing makes that other piece of code wait at all, no matter whether the above code has obtained a lock or not.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!