views:

1552

answers:

4

In my understanding of Servlet, the Servlet will be instantiated by the Container, his init() method will be called once, and the servlet will live like a singleton until the jvm is shut down.

i do not expect my servlet to be serialized, since it will be constructed new when the app server recovers or is starting up normally. the servlet should hold no session-specific members, so it does not make sense for it to be written to disk and re-instantiated. is there a practical use for this?

my concerns are, that i put some non-serializable fields in there and then my app will mysteriously fail in a production environment where a different sort of session replication will take place.

+8  A: 

Technically, I believe the servlet container is allowed to "passivate" the servlet object to disk, in a similar way that EJB session beans can be. So you're correct to ask the question if your app will fail due to non-serializable fields.

In practise, I've never heard of a container doing this, so it's really just legacy baggage from the bad old days of early J2EE. I wouldn't worry about it.

skaffman
+1  A: 

Google seems to suggest that this was done so that container authors can have the option, if they want it.

You're correct that the servlet should hold no session-specific members, in fact I would think you'd want as little state at all as possible. If you store everything in either Session or ServletConfig, I think you'd be able to survive serialization.

matt b
Well the Session is far more likely to be serialized than the servlet, so storing it there wouldn't mitigate the problem.
skaffman
@matt b: the concern is not so much session-specific state as the servlet's own dependencies (e.g. service layer objects)
Andrew Swan
A: 

Just like Session objects are serialized to survive caches for those servletcontainers giving the cluster option, there might be an option for a container to transfer a Servlet instance as well to another cluster node ?? I'm just guessing here

anjanb
+2  A: 

HttpServlet should by serialized to disk and survive restart of servlet container. For example tomcat allows you to set up flag which enable this kind of survive. The next option is transfer using JNDI. This is not garbage, it is used only in extreme use cases.

Rastislav Komara