This is an automated email from the ASF dual-hosted git repository.

markt-asf pushed a commit to branch 11.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/11.0.x by this push:
     new d795e736fb Fix BZ 70241 - Cache the public methods used to resolve EL 
method calls (#1155)
d795e736fb is described below

commit d795e736fb05ff9d91f0c0ce325931c3c8ac863e
Author: Arturo Bernal <[email protected]>
AuthorDate: Tue Nov 17 18:06:43 2026 +0100

    Fix BZ 70241 - Cache the public methods used to resolve EL method calls 
(#1155)
    
    Evaluating an EL method invocation that has arguments called
    Class.getMethods() every time, which copies every public method of the
    class. For a class with 200 public methods this allocated about 20 KB for
    each evaluation. The fix for BZ 69381 added a fast path for methods
    without arguments only.
    
    Cache the result in a ClassValue in jakarta.el.Util and in
    org.apache.el.util.ReflectionUtil. A ClassValue is per class, so classes
    with the same name in different class loaders do not share an entry, and
    the entry is released with the class so the cache cannot prevent a web
    application class loader from being garbage collected.
---
 java/jakarta/el/Util.java                          |  16 +++-
 java/org/apache/el/util/ReflectionUtil.java        |  16 +++-
 test/jakarta/el/TestUtil.java                      |  43 +++++++++
 .../apache/el/TestMethodInvocationAllocation.java  | 105 +++++++++++++++++++++
 test/org/apache/el/TesterIsolatedClassLoader.java  |  85 +++++++++++++++++
 test/org/apache/el/util/TestReflectionUtil.java    |  26 +++++
 webapps/docs/changelog.xml                         |   4 +
 7 files changed, 293 insertions(+), 2 deletions(-)

diff --git a/java/jakarta/el/Util.java b/java/jakarta/el/Util.java
index 2718e2e4d5..94b56f59a8 100644
--- a/java/jakarta/el/Util.java
+++ b/java/jakarta/el/Util.java
@@ -74,6 +74,20 @@ class Util {
 
     private static final ExpressionFactoryCache factoryCache = new 
ExpressionFactoryCache();
 
+    /*
+     * Class.getMethods() returns a new copy of every public method each time 
it is called. A ClassValue rather than a
+     * Map is used to cache the result so that the cache does not prevent a 
class, and its class loader, from being
+     * garbage collected. The arrays are shared so they must not be modified.
+     *
+     * This cache is duplicated in org.apache.el.util.ReflectionUtil. When 
making changes keep the code in sync.
+     */
+    private static final ClassValue<Method[]> publicMethodsCache = new 
ClassValue<>() {
+        @Override
+        protected Method[] computeValue(Class<?> type) {
+            return type.getMethods();
+        }
+    };
+
     /**
      * Provides a per class loader cache of ExpressionFactory instances 
without pinning any in memory as that could
      * trigger a memory leak.
@@ -111,7 +125,7 @@ class Util {
             }
         }
 
-        Method[] methods = clazz.getMethods();
+        Method[] methods = publicMethodsCache.get(clazz);
 
         List<Wrapper<Method>> wrappers = Wrapper.wrap(methods, methodName);
 
diff --git a/java/org/apache/el/util/ReflectionUtil.java 
b/java/org/apache/el/util/ReflectionUtil.java
index e0c09d0dd7..aa3aa61349 100644
--- a/java/org/apache/el/util/ReflectionUtil.java
+++ b/java/org/apache/el/util/ReflectionUtil.java
@@ -47,6 +47,20 @@ public class ReflectionUtil {
     protected static final Class<?>[] PRIMITIVES = new Class[] { 
boolean.class, byte.class, char.class, double.class,
             float.class, int.class, long.class, short.class, Void.TYPE };
 
+    /*
+     * Class.getMethods() returns a new copy of every public method each time 
it is called. A ClassValue rather than a
+     * Map is used to cache the result so that the cache does not prevent a 
class, and its class loader, from being
+     * garbage collected. The arrays are shared so they must not be modified.
+     *
+     * This cache is duplicated in jakarta.el.Util. When making changes keep 
the code in sync.
+     */
+    private static final ClassValue<Method[]> publicMethodsCache = new 
ClassValue<>() {
+        @Override
+        protected Method[] computeValue(Class<?> type) {
+            return type.getMethods();
+        }
+    };
+
     private ReflectionUtil() {
         super();
     }
@@ -188,7 +202,7 @@ public class ReflectionUtil {
             return result;
         }
 
-        Method[] methods = clazz.getMethods();
+        Method[] methods = publicMethodsCache.get(clazz);
         Map<Method,MatchResult> candidates = new HashMap<>();
 
         for (Method m : methods) {
diff --git a/test/jakarta/el/TestUtil.java b/test/jakarta/el/TestUtil.java
index 3ed53f5b6b..ecb3278188 100644
--- a/test/jakarta/el/TestUtil.java
+++ b/test/jakarta/el/TestUtil.java
@@ -16,11 +16,14 @@
  */
 package jakarta.el;
 
+import java.lang.ref.WeakReference;
 import java.util.Date;
 
 import org.junit.Assert;
 import org.junit.Test;
 
+import org.apache.el.TesterIsolatedClassLoader;
+
 public class TestUtil {
 
     @Test
@@ -53,4 +56,44 @@ public class TestUtil {
         processor.defineBean("string", "Not used. Any value is fine here");
         Assert.assertEquals("5", processor.eval("string.valueOf(5)"));
     }
+
+    /*
+     * The cache of public methods must not prevent a class, or its class 
loader, from being garbage collected.
+     */
+    @Test
+    public void testMethodLookupDoesNotPreventClassUnloading() throws 
Exception {
+        WeakReference<ClassLoader> reference = invokeMethodOfIsolatedClass();
+        Assert.assertTrue("The class loader was not garbage collected",
+                TesterIsolatedClassLoader.awaitCollection(reference));
+    }
+
+
+    private WeakReference<ClassLoader> invokeMethodOfIsolatedClass() throws 
Exception {
+        ClassLoader loader = new 
TesterIsolatedClassLoader(TesterIsolatedClassLoader.Target.class);
+        Object bean = 
loader.loadClass(TesterIsolatedClassLoader.Target.class.getName()).getDeclaredConstructor()
+                .newInstance();
+        ELProcessor processor = new ELProcessor();
+        processor.defineBean("target", bean);
+        // Looking up a method with an argument populates the cache. Do it 
twice to use the cached value.
+        Assert.assertEquals("a", processor.eval("target.echo('a')"));
+        Assert.assertEquals("b", processor.eval("target.echo('b')"));
+        return new WeakReference<>(loader);
+    }
+
+
+    /*
+     * Classes with the same name in different class loaders must not share 
cached methods.
+     */
+    @Test
+    public void testMethodLookupWithSameClassNameInDifferentClassLoaders() 
throws Exception {
+        for (int i = 0; i < 2; i++) {
+            ClassLoader loader = new 
TesterIsolatedClassLoader(TesterIsolatedClassLoader.Target.class);
+            Object bean = 
loader.loadClass(TesterIsolatedClassLoader.Target.class.getName()).getDeclaredConstructor()
+                    .newInstance();
+            ELProcessor processor = new ELProcessor();
+            processor.defineBean("target", bean);
+            Assert.assertEquals("a" + i, processor.eval("target.echo('a" + i + 
"')"));
+            Assert.assertEquals("b" + i, processor.eval("target.echo('b" + i + 
"')"));
+        }
+    }
 }
diff --git a/test/org/apache/el/TestMethodInvocationAllocation.java 
b/test/org/apache/el/TestMethodInvocationAllocation.java
new file mode 100644
index 0000000000..96f7727418
--- /dev/null
+++ b/test/org/apache/el/TestMethodInvocationAllocation.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.el;
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.util.concurrent.ConcurrentHashMap;
+
+import jakarta.el.ELContext;
+import jakarta.el.ExpressionFactory;
+import jakarta.el.MethodExpression;
+import jakarta.el.StandardELContext;
+import jakarta.el.ValueExpression;
+
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Test;
+
+/**
+ * Checks that evaluating an EL method invocation that has arguments does not 
copy every public method of the class on
+ * each evaluation. The test measures the memory allocated by the thread so, 
unlike a test of elapsed time, the result
+ * does not depend on the speed of the machine.
+ */
+public class TestMethodInvocationAllocation {
+
+    private static final int WARM_UP = 20000;
+    private static final int ITERATIONS = 20000;
+
+
+    @Test
+    public void testValueExpressionMethodWithArgument() {
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = createContext(factory);
+        ValueExpression expression = factory.createValueExpression(context, 
"${map.containsKey('a')}", Object.class);
+
+        Assert.assertEquals(Boolean.FALSE, expression.getValue(context));
+        assertAllocationBelowCopyOfMethods(() -> expression.getValue(context));
+    }
+
+
+    @Test
+    public void testMethodExpressionWithArgument() {
+        ExpressionFactory factory = ExpressionFactory.newInstance();
+        ELContext context = createContext(factory);
+        MethodExpression expression = factory.createMethodExpression(context, 
"${map.containsKey('a')}",
+                Object.class, new Class<?>[0]);
+
+        Assert.assertEquals(Boolean.FALSE, expression.invoke(context, null));
+        assertAllocationBelowCopyOfMethods(() -> expression.invoke(context, 
null));
+    }
+
+
+    private static ELContext createContext(ExpressionFactory factory) {
+        StandardELContext context = new StandardELContext(factory);
+        context.getVariableMapper().setVariable("map",
+                factory.createValueExpression(new 
ConcurrentHashMap<String,String>(), Object.class));
+        return context;
+    }
+
+
+    private static void assertAllocationBelowCopyOfMethods(Runnable 
evaluation) {
+        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
+        Assume.assumeTrue(bean instanceof com.sun.management.ThreadMXBean);
+        com.sun.management.ThreadMXBean allocationBean = 
(com.sun.management.ThreadMXBean) bean;
+        Assume.assumeTrue(allocationBean.isThreadAllocatedMemorySupported());
+        long threadId = Thread.currentThread().getId();
+
+        // The memory allocated each time Class.getMethods() copies the public 
methods of the class
+        Class<?> clazz = ConcurrentHashMap.class;
+        clazz.getMethods();
+        long start = allocationBean.getThreadAllocatedBytes(threadId);
+        for (int i = 0; i < 1000; i++) {
+            clazz.getMethods();
+        }
+        long copyOfMethods = (allocationBean.getThreadAllocatedBytes(threadId) 
- start) / 1000;
+        // The check is only meaningful if copying the methods allocates a lot
+        Assume.assumeTrue(copyOfMethods > 5000);
+
+        for (int i = 0; i < WARM_UP; i++) {
+            evaluation.run();
+        }
+        start = allocationBean.getThreadAllocatedBytes(threadId);
+        for (int i = 0; i < ITERATIONS; i++) {
+            evaluation.run();
+        }
+        long perEvaluation = (allocationBean.getThreadAllocatedBytes(threadId) 
- start) / ITERATIONS;
+
+        Assert.assertTrue("Allocated [" + perEvaluation + "] bytes for each 
evaluation. Copying the methods of the class"
+                + " allocates [" + copyOfMethods + "] bytes", perEvaluation < 
copyOfMethods / 2);
+    }
+}
diff --git a/test/org/apache/el/TesterIsolatedClassLoader.java 
b/test/org/apache/el/TesterIsolatedClassLoader.java
new file mode 100644
index 0000000000..dd1294f06c
--- /dev/null
+++ b/test/org/apache/el/TesterIsolatedClassLoader.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.el;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.ref.WeakReference;
+
+/**
+ * Defines a copy of a single class in a class loader of its own so that tests 
can check that the class, and therefore
+ * the class loader, is not kept in memory by a cache.
+ */
+public class TesterIsolatedClassLoader extends ClassLoader {
+
+    private final String isolatedClassName;
+
+
+    public TesterIsolatedClassLoader(Class<?> isolatedClass) {
+        super(isolatedClass.getClassLoader());
+        this.isolatedClassName = isolatedClass.getName();
+    }
+
+
+    @Override
+    protected Class<?> loadClass(String name, boolean resolve) throws 
ClassNotFoundException {
+        if (!isolatedClassName.equals(name)) {
+            return super.loadClass(name, resolve);
+        }
+        synchronized (getClassLoadingLock(name)) {
+            Class<?> result = findLoadedClass(name);
+            if (result == null) {
+                try (InputStream is = 
getParent().getResourceAsStream(name.replace('.', '/') + ".class")) {
+                    byte[] bytes = is.readAllBytes();
+                    result = defineClass(name, bytes, 0, bytes.length);
+                } catch (IOException e) {
+                    throw new ClassNotFoundException(name, e);
+                }
+            }
+            return result;
+        }
+    }
+
+
+    /**
+     * Waits until the referenced object has been garbage collected.
+     *
+     * @param reference The reference to the object
+     *
+     * @return {@code true} if the object was garbage collected, otherwise 
{@code false}
+     *
+     * @throws InterruptedException If the thread is interrupted while waiting
+     */
+    public static boolean awaitCollection(WeakReference<?> reference) throws 
InterruptedException {
+        for (int i = 0; i < 50 && reference.get() != null; i++) {
+            System.gc();
+            Thread.sleep(100);
+        }
+        return reference.get() == null;
+    }
+
+
+    /**
+     * The class that is defined in an isolated class loader.
+     */
+    public static class Target {
+
+        public String echo(String value) {
+            return value;
+        }
+    }
+}
diff --git a/test/org/apache/el/util/TestReflectionUtil.java 
b/test/org/apache/el/util/TestReflectionUtil.java
index 1d2e04f7a1..aa90feb80c 100644
--- a/test/org/apache/el/util/TestReflectionUtil.java
+++ b/test/org/apache/el/util/TestReflectionUtil.java
@@ -16,6 +16,8 @@
  */
 package org.apache.el.util;
 
+import java.lang.ref.WeakReference;
+
 import jakarta.el.ELContext;
 import jakarta.el.ExpressionFactory;
 import jakarta.el.MethodExpression;
@@ -24,6 +26,7 @@ import jakarta.el.MethodNotFoundException;
 import org.junit.Assert;
 import org.junit.Test;
 
+import org.apache.el.TesterIsolatedClassLoader;
 import org.apache.jasper.el.ELContextImpl;
 
 public class TestReflectionUtil {
@@ -82,4 +85,27 @@ public class TestReflectionUtil {
 
         Assert.assertEquals("2", result);
     }
+
+    /*
+     * The cache of public methods must not prevent a class, or its class 
loader, from being garbage collected.
+     */
+    @Test
+    public void testMethodLookupDoesNotPreventClassUnloading() throws 
Exception {
+        WeakReference<ClassLoader> reference = findMethodOfIsolatedClass();
+        Assert.assertTrue("The class loader was not garbage collected",
+                TesterIsolatedClassLoader.awaitCollection(reference));
+    }
+
+
+    private WeakReference<ClassLoader> findMethodOfIsolatedClass() throws 
Exception {
+        ClassLoader loader = new 
TesterIsolatedClassLoader(TesterIsolatedClassLoader.Target.class);
+        Class<?> target = 
loader.loadClass(TesterIsolatedClassLoader.Target.class.getName());
+        Object bean = target.getDeclaredConstructor().newInstance();
+        // Look up the method twice to use the cached value on the second 
lookup
+        for (int i = 0; i < 2; i++) {
+            Assert.assertEquals(target, ReflectionUtil.getMethod(null, bean, 
"echo", new Class<?>[] { String.class },
+                    new Object[] { "a" }).getDeclaringClass());
+        }
+        return new WeakReference<>(loader);
+    }
 }
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index fd023d96f4..1150d4a868 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -206,6 +206,10 @@
         when calling an EL function. Pull request <pr>1130</pr> by Mykola
         Pavluchynskyi. (markt)
       </fix>
+      <fix>
+        <bug>70241</bug>: Cache the public methods used to resolve EL method
+        calls. Pull request <pr>1155</pr> provided by Arturo Bernal. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Cluster">


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to