title: Xpath memory leak?
body: <p>There appears to be a memory leak when using the standard Java library (1.6.0_27) for evaluating XPath expressions.</p>
  
  <p>See below for some code to reproduct this problem:</p>
  
  <pre><code>public class XpathTest {
  
      public static void main(String[] args) throws Exception {
          DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
          docFactory.setNamespaceAware(true);
          DocumentBuilder builder = docFactory.newDocumentBuilder();
          Document doc = builder.parse("test.xml");
  
          XPathFactory factory = XPathFactory.newInstance();
          XPath xpath = factory.newXPath();
          XPathExpression expr = xpath.compile("//Product");
  
          Object result = expr.evaluate(doc, XPathConstants.NODESET);
          NodeList nodes = (NodeList) result;
          for (int i = 0; i &lt; nodes.getLength(); i++) {
              Node node = nodes.item(i);
              System.out.println(node.getAttributes().getNamedItem("id"));
  
              XPathExpression testExpr = xpath.compile("Test");
              Object testResult = testExpr.evaluate(node, XPathConstants.NODE);
              Node test = (Node) testResult;
              System.out.println(test.getTextContent());
          }
          System.out.println(nodes.getLength());
      }
  }
  </code></pre>
  
  <p>An example XML file is given below:</p>
  
  <pre><code>&lt;Products&gt;
    &lt;Product id='ID0'&gt;
      &lt;Test&gt;0&lt;/Test&gt;
    &lt;/Product&gt;
    &lt;Product id='ID1'&gt;
      &lt;Test&gt;1&lt;/Test&gt;
    &lt;/Product&gt;
    &lt;Product id='ID2'&gt;
      &lt;Test&gt;2&lt;/Test&gt;
    &lt;/Product&gt;
    &lt;Product id='ID3'&gt;
      &lt;Test&gt;3&lt;/Test&gt;
    &lt;/Product&gt;
    ...
  &lt;/Products&gt;
  </code></pre>
  
  <p>When I run this example using the NetBeans profiler it appears that the allocations for the com.sun.org.apache.xpath.internal.objects.XObject class keeps increasing, even after garbage collection.</p>
  
  <p>Am I using the XPath library in an incorrect way? Is this a bug in the Java libraries? Are there are potential workarounds?</p>