使用標準Java庫(1.6.0_27)評估XPath表達式時,似乎存在內存泄漏。Xpath內存泄漏?
請參閱以下一些代碼來reproduct這個問題:
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 < 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());
}
}
一個示例XML文件如下:
<Products>
<Product id='ID0'>
<Test>0</Test>
</Product>
<Product id='ID1'>
<Test>1</Test>
</Product>
<Product id='ID2'>
<Test>2</Test>
</Product>
<Product id='ID3'>
<Test>3</Test>
</Product>
...
</Products>
當我運行使用它看來,分配對NetBeans Profiler這個例子com.sun.org.apache.xpath.internal.objects.XObject類不斷增加,即使在垃圾回收之後。
我是否以錯誤的方式使用XPath庫?這是Java庫中的錯誤嗎?是否有潛在的解決方法?
嗯,這將會非常有趣。你是如何測試你的假設的?用探查器?您的示例XML文件有多長時間?很可能有一個內部高速緩存來加速對「評估」的後續調用... –
示例XML文件具有100,000條記錄。我正在使用NetBeans分析器,並且爲文件com.sun.org.apache.xpath.internal.objects.XObject分配的對象在分析文件時不斷增加。 – Bob
這是很多記錄。對於性能(不僅是內存)的原因,你應該避免使用XPath,並儘量使用DOM API(另請參閱[我的基準測試](http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-實施績效))。 –