• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

servlet session thread safety ?

 
Raju Sri
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • 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
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic