This is an automated email from the ASF dual-hosted git repository.
markt-asf pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/9.0.x by this push:
new 65d0d9f854 Fix BZ 70241 - Cache the public methods used to resolve EL
method calls (#1155)
65d0d9f854 is described below
commit 65d0d9f85424f530156c7d478ec953b63e5394d9
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/javax/el/Util.java | 16 +++-
java/org/apache/el/util/ReflectionUtil.java | 16 +++-
test/javax/el/TestUtil.java | 43 +++++++++
.../apache/el/TestMethodInvocationAllocation.java | 105 +++++++++++++++++++++
test/org/apache/el/TesterIsolatedClassLoader.java | 98 +++++++++++++++++++
test/org/apache/el/util/TestReflectionUtil.java | 26 +++++
webapps/docs/changelog.xml | 4 +
7 files changed, 306 insertions(+), 2 deletions(-)
diff --git a/java/javax/el/Util.java b/java/javax/el/Util.java
index 564bb678e0..7e214c5eb4 100644
--- a/java/javax/el/Util.java
+++ b/java/javax/el/Util.java
@@ -97,6 +97,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<Method[]>() {
+ @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.
@@ -134,7 +148,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 5cc70804e0..bdb3e0cabc 100644
--- a/java/org/apache/el/util/ReflectionUtil.java
+++ b/java/org/apache/el/util/ReflectionUtil.java
@@ -49,6 +49,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<Method[]>() {
+ @Override
+ protected Method[] computeValue(Class<?> type) {
+ return type.getMethods();
+ }
+ };
+
private ReflectionUtil() {
super();
}
@@ -190,7 +204,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/javax/el/TestUtil.java b/test/javax/el/TestUtil.java
index 536771c7e2..b2d067c65b 100644
--- a/test/javax/el/TestUtil.java
+++ b/test/javax/el/TestUtil.java
@@ -16,11 +16,14 @@
*/
package javax.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..24dac6f6ef
--- /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 javax.el.ELContext;
+import javax.el.ExpressionFactory;
+import javax.el.MethodExpression;
+import javax.el.StandardELContext;
+import javax.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..a32b40744e
--- /dev/null
+++ b/test/org/apache/el/TesterIsolatedClassLoader.java
@@ -0,0 +1,98 @@
+/*
+ * 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.ByteArrayOutputStream;
+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 = readFully(is);
+ result = defineClass(name, bytes, 0, bytes.length);
+ } catch (IOException e) {
+ throw new ClassNotFoundException(name, e);
+ }
+ }
+ return result;
+ }
+ }
+
+
+ private static byte[] readFully(InputStream is) throws IOException {
+ byte[] buf = new byte[1024];
+ try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ int read;
+ while ((read = is.read(buf)) >= 0) {
+ out.write(buf, 0, read);
+ }
+ return out.toByteArray();
+ }
+ }
+
+
+ /**
+ * 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 4dacbac2a9..4e35db65c7 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 javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
@@ -24,6 +26,7 @@ import javax.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 6bb1f462b5..5864fee797 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]