On Head First Servlet P199's dialog on the thread-safety issues. The last comment says 'must synchronize on HttpSession'. I think this is not necessary. 2 threads can use any arbitrary objects to synchronize the access to shared resources. Am I right?
I don't have the book with me but this is my guess. Yes you are technically correct, but if you think about it, I think the authors intention is more that the easiest way is to synchronise on the HttpSession object otherwise you will need to come up with a common (comm across threads that is) object that you can synchronise on. This is not always an easy task.
if you use any arbitrary object as lock to control the access to the shared resource wrapped by a java object and stored in the HttpSession object,then when some thread comes into the synchronized block and use this object,in this case you can't ensure that the object isn't changed by another thread,because this object can be used in other places.as a example, user open two windows and the will visit two threads,one changed the value of the object, and the other cannot be informed.so the lock has to be the HttpSesion object.
do as you do.<br />SCJP 1.4<br />SCWCD 1.4<br />SCEA (in process)
I think that you're wrong. You must synchronize on HttpSession. That's because it's the only object that you really have bound to a client and accessible throughout various requests (this is called scope). Any other object you would have to use the HttpSession to get it, and then synchronize on it, but think about it - you already are accessing the HttpSession, unsynchronized.
<b><i>Bengt Hammarlund</i><br />� Sun Certified Java Programmer</b>