File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Thread safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Thread safe" Watch "Thread safe" New topic

Thread safe

benjik wang

Joined: Mar 06, 2006
Posts: 10
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

Joined: Apr 07, 2006
Posts: 20
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.

Regards,<br />SCJA<br />SCJP 1.4<br />SCWCD 1.4<br />SCBCD or SCEA - coming soon!
Manikandan Jayaraman
Ranch Hand

Joined: Sep 15, 2004
Posts: 230
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.


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,<br />Mani<br />SCJP 1.4 (95%)<br />SCWCD 1.4 (94%)
benjik wang

Joined: Mar 06, 2006
Posts: 10
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?
I agree. Here's the link:
subject: Thread safe
It's not a secret anymore!