You do not need to block because session.setAttribute() is thread safe (see @McDowell's servlet specification comment above).
However, use another example. Say you would like to reread the attribute value and then update it if <= 100. In this case, you will need to synchronize the code block for getAttribute() compare <= 100 and setAttribute() .
Now what should you use to block? Remember that synchronization does not occur if different objects are used for locking. Therefore, different code blocks must use the same object. Your choice of session object can be wonderful. Remember also that different code blocks can access the session (both read and write), even if you made a lock, if this other code also does not block the session object. The catch here is that too many places in your code block the session object and therefore must wait. For example, if your code block uses session attribute A and another piece of code uses session attribute B, it would be nice if they did not need to wait from each other, making a lock on the session object. Using static objects named LockForA and LockForB might be the best choice for using your code β for example, synchronized (LockForA) { }.
Ken H Nov 10 2018-11-11T00: 00Z
source share