使用标准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-实施绩效))。 –