• 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

servlet session thread safety ?

 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I am preparing for SCWCD 1.4 and reading Servlets and JavaServer Pages book by Jayson and Kevin.In the book it is mentioned about thread safety of session object like below

***********************************************************************
Both the HttpSession object and ServletContext object are shared resouces.The ServletContext object can be accessed by many Servers or JSP at the same time.The HttpSession object can be accessed at the same time by two different requests from a client.In uses of both objects proper synchronization should be used.

The simplest solution to providing accurate session and application in state is to always wrap access to the associated object in a synchronized block.Listing below demonstrates wrapping a session access using a synchronization block.

User user=new User();
HttpSession session = request.getSession(true);
synchronized(session) {
session.setAttribute("user",user);
}
**********************************************************************

Here my question is why we need to synchronized session object.I think it is already thread safe object . Why I am thinking like this is because request and response objects are always thread safe objects.So here we are getting session from request object. so that doen't that mean session is thread safe object ??

Thanks in advance
Raju
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The request and response objects are obviously thread-safe since they are only associated with one single thread of execution. But, that doesn't mean that the session they are associated with is thread-safe. (Bad logic there!!). As you mentioned, sessions are visible from across all requests. So, request1.getSession() == request2.getSession()!! So, if you do crazy stuff with your sessions, you need to synchronize some stuff.
 
I don't even know how to spell CIA. But this tiny ad does:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic