3

For example a user may access a servlet and that servlet has a series of actions regarding session which may take some time. At the mean time the user opens another window and visits another servlet regarding session. Since these two servlets are visited by the same user, they use the same session variables. So I think there tend to be synchonization problems.

If there exist such problems, is using sychronized block along enough to solve the issue? (I think sychronized block can only deal with things in the same thread.)

NSF
  • 2,499
  • 6
  • 31
  • 55
  • 2
    Synchronized block is meant to serialize access to a code block, by multiple threads. – Vikdor Sep 16 '12 at 05:40
  • See answer by McDowell here http://stackoverflow.com/questions/616601/is-httpsession-thread-safe-are-set-get-attribute-thread-safe-operations – Kurtcebe Eroglu Sep 16 '12 at 06:17

1 Answers1

2

The session itself is thread-safe. But that doesn't mean that using it without any kind of synchronization leads to correct behavior. It only means that the session will behave correctly if accessed by multiple threads.

For example, assume you have the following code executed concurrently:

Integer visitCount = (Integer) session.getAttribute("visitCount");
visitCount = Integer.valueOf(visitCount.intValue() + 1);
session.setAttribute("visitCount", visitCount);

And assume the original value of visitCount is 0. The end result could be 2 (the expected value), or it could be 1. Indeed, both threads could read the current value conncurrently (0), then both increment it to 1, and both store it in the session.

Similarly, if you store a thread-unsafe object in the session (like a HashMap for example), and two threads use this HashMap concurrently, you could see erratic behavior.

As with every multi-threaded program, you must use appropriate synchronization mechanisms when necessary, and/or make your objects thread-safe. But this is the subject for a whole book. I would recommend Java Concurrency in practice.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255