Pardon me for my lack of knowledge .I had a query and wanted to discuss with fellow ranchers.
Does the above code
a) Synchronize mySession object ?
b) Do we even need the synchronized block.As each request goes as a new thread.
Can anyone clarify this doubt?
Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a thread safe manner. The Developer has the responsibility for thread safe access to the attribute objects themselves. This will protect the attribute collection inside the HttpSession object from concurrent access, eliminating the opportunity for anapplication to cause that collection to become corrupted.
So thread-safety of getAttribute() / setAttribute() calls should be guarenteed by the container, but thread-safe manipulation of the attribute itself is up to you.
In your case simply setting an immutable object as an attribute should be safe, regardless of additional synchornization - the synchonized block is not necessary.
If you were to get, modify and set a mutable object it would be a different matter, and synchronizing on the HttpSession instance might not be good enough in that case.
I don't believe there's any restriction specifying that a container must provide the same HttpSession instance for the same session(id) - though in practice I guess most containers probably do.
You would not normally synchronize at the session level, because each user has a session independent from every other user, except in cases where the user doesn't have a session at all (see above!).
So more commonly you would synchronize at application scope, and only worry about session-scope synchronization in cases where overlapping requests for the same user likely to occur. At human speeds, doing human workflows, that's rarely a problem, so mostly it would be automated clients that would be at risk.