From 87f26e57e75c70aeec3a3661dd019c8b44d6f7ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Mart=C3=ADn=20Sotuyo=20Dodero?= Date: Mon, 14 Nov 2016 00:09:49 -0300 Subject: [PATCH] Use a LRU cache in SaxonXPathRuleQuery --- .../lang/rule/xpath/SaxonXPathRuleQuery.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/SaxonXPathRuleQuery.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/SaxonXPathRuleQuery.java index 6321a64924..372334b4a2 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/SaxonXPathRuleQuery.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/SaxonXPathRuleQuery.java @@ -4,7 +4,7 @@ package net.sourceforge.pmd.lang.rule.xpath; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -41,6 +41,15 @@ public class SaxonXPathRuleQuery extends AbstractXPathRuleQuery { private XPathExpression xpathExpression; private List xpathVariables; + private static final int MAX_CACHE_SIZE = 20; + private static final Map CACHE = new LinkedHashMap(MAX_CACHE_SIZE) { + private static final long serialVersionUID = -7653916493967142443L; + + protected boolean removeEldestEntry(final Map.Entry eldest) { + return size() > MAX_CACHE_SIZE; + } + }; + /** * {@inheritDoc} */ @@ -117,8 +126,6 @@ public class SaxonXPathRuleQuery extends AbstractXPathRuleQuery { return results; } - private static final Map CACHE = new HashMap<>(); - private DocumentNode getDocumentNode(Node node) { // Get the root AST node Node root = node; @@ -126,17 +133,12 @@ public class SaxonXPathRuleQuery extends AbstractXPathRuleQuery { root = root.jjtGetParent(); } - // Cache DocumentNode trees, so that different XPath queries can re-use - // them. - // Ideally this would be an LRU cache. + // Cache DocumentNode trees, so that different XPath queries can re-use them. DocumentNode documentNode; synchronized (CACHE) { documentNode = CACHE.get(root); if (documentNode == null) { documentNode = new DocumentNode(root); - if (CACHE.size() > 20) { - CACHE.clear(); - } CACHE.put(root, documentNode); } }