This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Confusion in code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Confusion in code" Watch "Confusion in code" New topic
Author

Confusion in code

Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105
Hi,

I've little confusion in the following code of head first book page no. 197.


I don't understand why they've used synchronized(getServletContext()) instead of just synchronized(this)? what's the reason?

Thanks in advance.
Chiranjeevi Kanthraj
Ranch Hand

Joined: Feb 18, 2008
Posts: 289

synchronized(getServletContext()) instead of just synchronized(this)? what's the reason?


Here "this" means Servlet which have the doGet() where we cont predict the Thread safety of the context object, so we have to lock that using servletContext

you can see int the bottom right corner in the Box, that is it will compile but not solve that problem.


-Chiru
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874




Here you are setting the attributes of the ServletContext , which can be accessed simultaneously in another servlet object. So you got to synchronize the ServletContext object as whole and not the servlet(this) object.


Nishan Patel
Ranch Hand

Joined: Sep 07, 2008
Posts: 684


Hi,

Synchronize basically apply on method or object when you write this means they consider that class object only...

But here you are using ServletContext object which is one for one application.

That is why you are using synchronized(getServletContext()) instead of just synchronized(this)




Thanks, Nishan Patel
SCJP 1.5, SCWCD 1.5, OCPJWSD Java Developer,My Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusion in code
 
Similar Threads
Session
Synchronizing getServletContext
difference between these methods...
Question of synchronizing HttpSession
getAttribute()