Search code examples
javaservletshttpsession

HttpSession stores attribute by reference or value?


I use HttpSession in my server application. And for the session set attributes. My question in next: how attribute for session sets - by reference or value.

Question in afraid reason that would not java heap space exception and RAM saving.

For example: if I'll create stateless array1 and will set this as attribute for the different sessions. In this case all sessions will work with array1 as "singleton" instance or maybe not

Thanks!


Solution

  • All objects (including arrays) are passed by reference in Java. So if you store the same instance of an array into multiple HttpSessions, it will be shared among them. The size of an array cannot be modified, however its elements can be - whether they are primitives or references, so you must be careful in highly concurrent environments such as Servlets.

    Another aspect you may want to take care of is that all attributes of an HttpSession should be serializable.