Is there some effective and accurate way to track the size of a particular session in a servlet based application?
Asked
Active
Viewed 281 times
1 Answers
0
Java doesn't have a sizeof()
method like C (see this post for more information) so you generally can't get the size of anything in Java. However, you can track what goes into and is removed from the session with a HttpSessionAttributeListener (link is JavaEE 8 and below). This will give you some visibility into the number of attributes and, to an extent, the amount of memory being used. Something like:
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been added" );
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.our.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been removed" );
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been replaced" );
}
}

stdunbar
- 16,263
- 11
- 31
- 53
-
1You can also serialize a session to bytes (or onto the disk) and look at how big the output is. This doesn't map directly to object-size-in-memory but it will be in the same ballpark. – Christopher Schultz Feb 16 '22 at 15:08