Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion in code

 
Pawan Arora
Ranch Hand
Posts: 105
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 290
Hibernate Spring Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 874
Android Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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
Posts: 689
Eclipse IDE Java Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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)



 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic