That depends on what your expectations are.
The first example from the book suggests that their expectation is that the value printed
must be the same as the value you put into the session. If the read value must be the same as the written value then you need to put both the read and write in the same synchronized block. Why? If you write "42" to bar, then exit the synchronized block another
thread could gain entry to the session, change the value to "21". Then when you try to read bar you get "21" instead of "42" as would be expected. Or worse the second thread could clear the attribute from the session so you would get null.
BTW, you could still shorten the synchronize block by using local variables:
But that sort of short circuits the example.