From 6faedcf6da95d8fede2dbecbbddcfdf21f82984c Mon Sep 17 00:00:00 2001 From: Arun Date: Sat, 11 Jul 2026 06:05:58 +0530 Subject: [PATCH] Use ConcurrentHashMap for XSLT template cache and add double-check locking --- .../struts2/result/xslt/XSLTResult.java | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/plugins/xslt/src/main/java/org/apache/struts2/result/xslt/XSLTResult.java b/plugins/xslt/src/main/java/org/apache/struts2/result/xslt/XSLTResult.java index b6d8ec62ac..76af97f4f9 100644 --- a/plugins/xslt/src/main/java/org/apache/struts2/result/xslt/XSLTResult.java +++ b/plugins/xslt/src/main/java/org/apache/struts2/result/xslt/XSLTResult.java @@ -45,7 +45,7 @@ import java.io.IOException; import java.io.PrintWriter; import java.net.URL; -import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; import java.util.Map; /** @@ -68,11 +68,7 @@ public class XSLTResult implements Result { /** * Cache of all templates. */ - private static final Map templatesCache; - - static { - templatesCache = new HashMap<>(); - } + private static final Map templatesCache = new ConcurrentHashMap<>(); // Configurable Parameters @@ -283,19 +279,23 @@ protected Templates getTemplates(final String path) throws TransformerException, if (noCache || (templates == null)) { synchronized (templatesCache) { - URL resource = ServletActionContext.getServletContext().getResource(path); - - if (resource == null) { - throw new TransformerException("Stylesheet " + path + " not found in resources."); + // Re-check after acquiring lock to avoid redundant compilation + templates = templatesCache.get(path); + if (noCache || (templates == null)) { + URL resource = ServletActionContext.getServletContext().getResource(path); + + if (resource == null) { + throw new TransformerException("Stylesheet " + path + " not found in resources."); + } + + LOG.debug("Preparing XSLT stylesheet templates: {}", path); + + TransformerFactory factory = createTransformerFactory(); + factory.setURIResolver(getURIResolver()); + factory.setErrorListener(buildErrorListener()); + templates = factory.newTemplates(new StreamSource(resource.openStream())); + templatesCache.put(path, templates); } - - LOG.debug("Preparing XSLT stylesheet templates: {}", path); - - TransformerFactory factory = createTransformerFactory(); - factory.setURIResolver(getURIResolver()); - factory.setErrorListener(buildErrorListener()); - templates = factory.newTemplates(new StreamSource(resource.openStream())); - templatesCache.put(path, templates); } }