This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
If your clustering your servlets, then one of the considerations is not to store any state in your ServletContext. Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs.
Objects stored in a session should be serializable to support in-memory replication of sessions. Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable. Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests. Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database. Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs. Avoid using java.io.* because the files may not exist on all backend machines. Instead use getResourceAsStream().
If you have to store things in a servlet context attribute, and want them shared across a cluster then you need to make them move themselves. Assuming the things you put into servlet context attributes are serializable, and you are using servlet spec 2.3 or later, you could build a listener (deployed in the web.xml) that implements the ServletContextAttributeListener, and is somehow configured to know the topology of the cluster. So you would need your own transport mechanism and inter cluster messaging, like a file system temporary folder, or network communications, or jmx, something that would react to the attributeAdded, attributeRemoved attributeReplaced methods, that are fired and consumed by your listener when you stuff things onto the servlet context attributes, then ship them through serialization, then the coresponding listener on other nodes would unpack them. Though the sensibility of doing this requires more thought, as unlike session attributes, it is possible for collision of two or more sessions on different cluster nodes attempting to set the same servlet context attribute at the same time; it may be just as 'easy' to have a seperate tomcat instance that is not part of the cluster, and does not serve jsp pages, but acts as a shared application scoped sttribute storage bucket, implementing a setAttribute() and getAttribute() functionality using some RPC mechanism (soap, RMI)?
Error: Keyboard not attached. Press F1 to continue.