Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Safe Doubt

 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
synchronized (request.getSession())


Can anyone please explain the significance of the above statement?
 
Victor Dolirio
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, this statement will garantee that the session will be safe in a multithread enviroment - thread safe - by this block of code. Actually it�s used to prevent the session to be used by multiples requests in a multithreaded context ie. if any request use a attribute you can garantee that no others requests use the session while this code is using that, this way you can protect the session scoped attributes. This protection will occur only if all code snippets also synchronize the session. For more details, you can find this in the HFSJ book.
 
Santosh Raveendran
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shiaber

Session scope is not 100% Thread safe even though it sounds Strange, only request scoped variables and local variables are 100% thread safe

There can be scenarios like a person opening the same application from two browser tabs in that case the session is same for both tabs so for making the session scoped attributes 100% thread safe we use

synchronized (request.getSession())

Thanks
santhosh
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to make sure that all the data [Attributes] that you store in the session object to be thread-safe [Prevent 2 or more threads changing the data unexpectedly] then you must make sure you synchronize on session object wherever you read/write data to session object.


Request Object: When you store data on request object [as attributes] they are thread safe because for every thread [every request] a new request object will be created and hence every thread will be working on their copies of request object and hence request attributes. As a result threads cannot not modify data on each other request objects and hence are called thread-safe.

Local Variables: When you store data in local variables [as attributes] they are thread safe because for every thread will have its own call stack and hence each thread will have its own copy of local variable and will be working on its copy.


Further
Servlet Instance variables are not thread safe.
Servlet Class variables are not thread safe.
Data on session[HttpSession] object are not thread safe.
Data on ServletContext [application] object are not thread safe.

Hope its clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic