Precise Java Google
Home  | J2SE  | J2EE  | Book  | Free Books  | Contact
Chapter 1  | Chapter 2  | Chapter 3

Recipe 2.1: Removing HttpSession objects programmatically


HttpSession objects occupy memory until session timeout occurs even if the corresponding users session activities are completed.


HttpSession object is a special type of object available in Servlets and JSPs that you associate with each user and typically use it to store user's data.. In Java, you create and use objects but normally you do not need to remove them, since the garbage collector removes them from the memory in the background once they are un-referenced from the program. Unlike normal Java objects, HttpSession objects must be removed programmatically when the user logs off from the web site. Otherwise the Servlet container keeps them in the memory until the associated user has been inactive for a certain length of time, at which point the session timeout occurs (session timeout value is 30 minutes by default). At that time, the container allows the garbage collector to remove the session. That means that HttpSession objects occupy memory for at least the length of time specified in the default configuration timeout value unless you remove them programmatically.

For instance, let's consider two shopping cart applications-Application A and Application B - where Application A gets one hundred thousand users in a time span of 30 minutes with an average session size of 10KB and Application B gets two hundred thousand users in a time span of 30 minutes with an average session size of 10 KB. They occupy the memory as shown in Figure 4.1.

Here the important thing you should note is that an average user typically finishes his shopping cart activity before 30 minutes and spends most of his time browsing the catalogs or in other activity. If we assume that an average user spends 15 minutes in the shopping cart and then logs off by completing his purchase, then the associated HttpSession object will be kept in the memory 15 more minutes unnecessarily. However, Iif the average user's session is in memory for only 15 minutes, then the memory usage in a 30 minute period is reduced we redo the above calculations with a 15-minute time frame and calculate the memory occupied by HttpSession objects, it reduces the memory by half as shown in Figure 4.2.

As you can see, we could significantly improve the efficiency of the server by removing the sessions from memory as soon as the users complete their transactions.

So how can we remove the HttpSession objects from memory after the users complete their session activity?


You need to call HttpSession.invalidate() method when a user logs off from your web site in order to remove HttpSession object data from the memory. This invalidate() method removes the session from memory and improves overall application performance. The following code demonstrates the usage of this method.

In Listing 4.1, the doPost() method from CartServlet adds Cart objects to the HttpSession object.

Listing4.1 CartServlet’s doPost() method

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("Action");

if (action.equals("Add to Cart")) {
String sessionSize = request.getParameter("SessionSize");
HttpSession session = request.getSession(true); |#1 // get maximum key number
int key = 1;
java.util.Enumeration enum = session.getAttributeNames();

if (enum != null) {
while (enum.hasMoreElements()) {
Object name = enum.nextElement();

} // create a session object
Cart cart = null;

if (sessionSize.equals("5KB")) {
// create an approximate 5KB object
cart = new Cart(5120 / 2); |#2
} else
if (sessionSize.equals("10KB")) {
// create an approximate 10KB object
cart = new Cart(10240 / 2); |#3

// add cart in the HttpSession object
for (int i = 0; i < 5; i++) {
if (session != null) {
session.setAttribute(Integer.toString(key + i), cart); |#4
.forward(request, response); |#5
} else if (action.equals("Log Off")) {
.forward(request, response); |#6

(annotation)<#1 Get HttpSession object reference>
(annotation)<#2 Creates approximate 5KB Cart object>
(annotation)<#3 Creates approximate 10KB Cart object >
(annotation)<#4 Put Cart object in HttpSession object >
(annotation)<#5 Returns to CartClient>
(annotation)<#6 forward it to LogOff.jsp if the user action is Log Off>


In listing 4.2, LogOff.jsp calls the invalidate() method before it forwards the page.


Listing4.2 LogOff.jsp

<% session.invalidate(); %> |#1
<jsp:forward page="/CartClient.jsp" /> |#2

(annotation)<#1 Remove HttpSession object from the memory>
(annotation)<#2 Return to CartClient>



Each HttpSession object is available to both the JSPs and the Servlets in your web application. In JSP you can directly use the session implicit object where as in Servlet you need to call the HttpSession.getSession() method to get the HttpSession object reference.

This hows how many objects are created in HttpSession, how much memory each object takes, and how much memory usage is reduced with each invalidate() method call. In order to see the concurrent client accesses, open one or more browsers and run this example simultaneously, you will see different session object metrics.

Feed back

We appreciate and welcome your comments on this section. Email (remove ZZZ which is placed to prevent spam). Please note that we may not be able to reply to all the emails due to huge number of emails that we receive but we appreciate your comments and feedback.


Copyright © 2001-2005, Ravi Kalidindi and Rohini Kalidindi. All rights reserved.