I have some java code that gets and sets a session attribute:
Object obj = session.getAttribute(TEST_ATTR);
if (obj==null) {
obj = new MyObject();
sessio
You don't need to lock since session.setAttribute()
is thread safe (see servlet spec comment from @McDowell above).
However, let's use a different example. Let's say you wanted to chek the value of the attribute, then update it if <= 100. In this case you would need to syncronize the block of code for the getAttribute()
the compare <= 100 and the setAttribute()
.
Now, what should you use for the lock? Remember there is no syncronization if different objects are used for the lock. So different code blocks must use the same object. Your choice of the session
object may be just fine. Remember too that different code blocks may access the session (both read/write) even if you have taken a lock, unless that other code also locks on the session object. A pitfall here is that too many places in your code take a lock on the session object and thus have to wait. For example, if your code block uses session attribute A and another hunk of code uses session attribute B, it would be nice if they didn't need to wait on each other by both taking a lock on the session object. The use of static objects named LockForA, and LockForB might be better choices for your code to use - e.g. synchronized (LockForA) { }.