jQuery in Action, 3rd edition
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Confusion in code" Watch "Confusion in code" New topic

Confusion in code

Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105

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: 290

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.

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: 689


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
jQuery in Action, 3rd edition