This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread safe

 
benjik wang
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In page 197 of HFSJ, it says that "Synkronizing on the servletContext makes it thread-safe from any other code that also synkronizes on the servletContext". I am kind of confused. Is this a java rule? (i remmember that there is no such rule in plain java)
 
Srikanth shetty Nukala
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
the synchronising on servletcontext object makes the attributes stored in it threadsafe only IF all the other servlets which access these context attributes also synchronise on this object.

mutual exclusion works i.e at a time only one servlet will have access,, only if all the other servlets are synchronising on context object.

Because If a servlet uses the context attributes without synchronising on context object they are no more thread safe even if current servlet synchronises on context object.

hope i dint confuse u.

correct me if i am wrong.
 
Manikandan Jayaraman
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can synchronize on any object and that is available in "Threads" of SCJP too.

Here when we say that we synchronize on ServletContext, we say that we are placing a lock on the context and thus all attributes or objects bound to the context remains thread safe.

Yes, the catch is, all your servlets should get a lock on the servlet context, before performing any changes to the context attributes.

=====
Extension
=====

If we are very specific that a servelt say S1 accesses(or mutates) only attribute A1 bound with the context, then can we synchronize only on A1 instead of the entire context.

It makes me feel that the above approach will improve performance. Am I right? Please reply.

Regards,
Mani
 
benjik wang
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for reply. I am not sure if you can synkronize on an attribute of context or not. If you think context as a collection, an attribute (name/value pair) is just like an element of a collection. So the question will be if you can get a lock only on some element of a collection?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic