Propagating changed session data to a cluster
Written by Joseph Ottinger
If you have a cluster, changing an attribute in a session will no necessarily propagate to the cluster unless you do it properly.
Here's a sample container object:
public class ContainerObject implements java.io.Serializable {public int counter;
public void add() { counter++; } public int getCounter() { return counter; }}
Note that this class is for example purposes only - apart from the very limited functionality, it wouldn't actually work well, due to a lack of synchronization issues. Adding synchronized to the add() method would help a little, but it would only affect one JVM in the cluster. If two machines in the cluster happened to call add() at the same instant, there'd be no way for the synchronized keyword to know about monitors that exist elsewhere in the cluster.
In a servlet, assuming that an instance of ContainerObject has already been stored in an HttpSession, this code should work properly - as long as there's no cluster:
ContainerObject foo=session.getAttribute("container"); foo.add();
However, the new "container" reference will not get propagated. To propagate the new value (actually, the serialized representation of the object) to the rest of the cluster, you will need to call setAttribute(), so the following code should do the trick:
ContainerObject foo=session.getAttribute("container");foo.add();
session.setAttribute("container", foo);
Copyright © 2007 IronFlare AB