• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Confusion in code

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 290
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 874
Android VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Ranch Hand
Posts: 689
Scala Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)



 
reply
    Bookmark Topic Watch Topic
  • New Topic