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.
If happen something bad in you life, don't ask God why it happened. Ask for what.
SCJP 5 (80%) - SCWCD 5 (91%) - SCBCD & SCJD coming soon...
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
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.