Forums Register Login

Thread safe

+Pie Number of slices to send: Send
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)
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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?
Thanks tiny ad, for helping me escape the terrible comfort of this chair.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 928 times.
Similar Threads
Question On Thread Safety
About Servlets lifecycle...
Ajax callback doesn't initiate the servlet variable?
ServletContext.setAttribute() always need Synchronization
diffrence b/w calling of getRequestDispatcher form request and getServletCotext.
Request Attributes Thread Safe?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 06:23:29.