1

What does the transient Keyword exactly mean? I have a Class attribute marked as transient:

public class NodeClassifier {

   private transient HashMap<String, Node> nodeCache = new HashMap<>();

...
}

After storing and recovering an NodeClassifier Object into the HttpSession the Attribute still has the Value from previous Session.

Shouldn't it be empty?

The Environment is a plain Servlet running on Glassfish4.

Marko
  • 514
  • 1
  • 4
  • 16

1 Answers1

5

transient means that the value will not be serialized (using default Java object serialization), when the object is written out as bytes.

Serialization of a session may or may not happen (it is only needed to pass the session between processes, or to persist it to disk, but usually not needed in a single JVM servlet container that can just keep them in memory), so you should not rely on values being "lost" that way.

If you don't want stuff to survive in the session, don't put it there. Consider using request attributes instead.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    Ok, understood. It might be lost if the server decides to serialize but isn't lost if the server keeps session in memory, right? So transient is really only for limiting session storage. Is there a default way to clean attribute when putting something into the session? Some callback or similiar? Or do I need to code it manually. – Marko Sep 15 '16 at 09:57
  • 1
    Request attributes is not working for me, as it is a nested object structure and one object has a "cache" which needs to be cleard on persisting in session. – Marko Sep 15 '16 at 09:59
  • 1
    No, `transient` is a quite low-level mechanism to make serialization work. It is not intended to limit session storage. The session is supposed to store everything you put into it. – Thilo Sep 15 '16 at 10:00
  • 1
    If the existing scopes (session, request, page, ThreadLocal) are not enough for you, then, yes, you need to code it manually. You could certainly have a request filter to remove things from your session before or after each request gets processed. – Thilo Sep 15 '16 at 10:02
  • 1
    Ok, thanks. I have a "repository" class reading and writing this object from the session, I will add it there. – Marko Sep 15 '16 at 10:04