views:

256

answers:

3

Hi,

When a JSP finishes execution, will all variables declared in the JSP page be put up for garbage collection? If I declare a number of memory intensive Hashtables in the JSP, and I let the JSP finish execution without setting the variables to null beforehand, will the object stay in memory even after the JSP has finished executing?

(I am not storing them in a persistent variable, such as session. Just in a local variable.)

+3  A: 

If the variables are declared in request or page scope, yes they are eligible for garbage collection.

Even if you set an object reference to null it is still consuming memory, only the reference count decreases by 1. If the reference count is 0 the garbage collector will free the memory.

Kees de Kooter
Java does not use a refcounting GC.
jrockway
A: 

Well, the JSP engine removes the JSP page from the memory once the execution has finished (if the scope is not set to session). How ever, to avoid memory leaks you should use the jspDestroy() method to free memory.

Björn
A: 

If you want to find out exactly what Java logic code the JSP translates into, you can use Jasper to generate the code. (Different JSP engines will likely generate differing output, but the scope of variables and so on should conform to the spec.) You'll need Tomcat and Ant.

This sample batch script generates the Java code for test.jsp in the output directory:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET ANT_HOME=C:\dev\apache-ant-1.7.1
SET TOMCAT_HOME=C:\Program Files\Apache Software Foundation\Tomcat 6.0
SET CLASSPATH="
FOR /r "%TOMCAT_HOME%\bin\" %%a IN (*.jar) DO SET CLASSPATH=!CLASSPATH!;%%a
FOR /r "%TOMCAT_HOME%\lib\" %%a IN (*.jar) DO SET CLASSPATH=!CLASSPATH!;%%a
SET CLASSPATH=!CLASSPATH!;%ANT_HOME%\lib\ant.jar"
MKDIR output
java org.apache.jasper.JspC -d .\output -webapp .\WebContent test.jsp

WebContent is the root directory of the web application. The generated code is a servlet and will follow the servlet lifecycle as defined in the spec.

McDowell