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

chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-jsieve.git

commit 45aaa3c8cbfe453e3654deb63cd3b910690c58a3
Author: Benoit TELLIER <[email protected]>
AuthorDate: Wed Nov 18 22:28:49 2026 +0100

    [FIX] Managers: resolve an implementation class once
    
    CommandManagerImpl, TestManagerImpl and ComparatorManagerImpl called
    ClassLoader#loadClass on every lookup, and evaluation looks up every
    command, every test and, for each comparison, the comparator: the JVM
    interned the class name into its symbol table and took the class
    loading lock each time. This was 24-29% of the CPU of a typical filter
    script, 65% of evaluateNumericIs and 25% of a script parse.
    
    The managers now share an ImplementationCache keeping the constructor
    of each class, keyed by class name so that a name mapped to another
    class resolves to it. Failures are not cached. Each call still gets a
    new instance, as tests keep per-instance state.
---
 .../java/org/apache/jsieve/CommandManagerImpl.java |  22 +---
 .../org/apache/jsieve/ComparatorManagerImpl.java   |  23 +---
 .../org/apache/jsieve/ImplementationCache.java     | 124 +++++++++++++++++++++
 .../java/org/apache/jsieve/TestManagerImpl.java    |  23 +---
 .../org/apache/jsieve/ImplementationCacheTest.java | 119 ++++++++++++++++++++
 5 files changed, 255 insertions(+), 56 deletions(-)

diff --git a/core/src/main/java/org/apache/jsieve/CommandManagerImpl.java 
b/core/src/main/java/org/apache/jsieve/CommandManagerImpl.java
index 86d8d06..66d82b4 100644
--- a/core/src/main/java/org/apache/jsieve/CommandManagerImpl.java
+++ b/core/src/main/java/org/apache/jsieve/CommandManagerImpl.java
@@ -44,6 +44,8 @@ public class CommandManagerImpl implements CommandManager {
     }
 
     private final ConcurrentMap<String, String> classNameMap;
+    private final ImplementationCache<ExecutableCommand> implementations =
+            new ImplementationCache<>(ExecutableCommand.class, "Command", 
getClass().getClassLoader());
 
     /**
      * Constructor for CommandManager.
@@ -64,17 +66,7 @@ public class CommandManagerImpl implements CommandManager {
      * @throws LookupException
      */
     private Class lookup(String name) throws LookupException {
-        Class cmdClass;
-        try {
-            cmdClass = getClass().getClassLoader()
-                    .loadClass(getClassName(name));
-        } catch (ClassNotFoundException e) {
-            throw new LookupException("Command named '" + name + "' not 
found.");
-        }
-        if (!ExecutableCommand.class.isAssignableFrom(cmdClass))
-            throw new LookupException("Class " + cmdClass.getName()
-                    + " must implement " + ExecutableCommand.class.getName());
-        return cmdClass;
+        return implementations.lookup(name, getClassName(name));
     }
 
     /**
@@ -89,13 +81,7 @@ public class CommandManagerImpl implements CommandManager {
      * @throws LookupException
      */
     public ExecutableCommand getCommand(String name) throws LookupException {
-        try {
-            return (ExecutableCommand) lookup(name).newInstance();
-        } catch (InstantiationException e) {
-            throw new LookupException(e.getMessage());
-        } catch (IllegalAccessException e) {
-            throw new LookupException(e.getMessage());
-        }
+        return implementations.newInstance(name, getClassName(name));
     }
 
     /**
diff --git a/core/src/main/java/org/apache/jsieve/ComparatorManagerImpl.java 
b/core/src/main/java/org/apache/jsieve/ComparatorManagerImpl.java
index 3613a5f..144857c 100644
--- a/core/src/main/java/org/apache/jsieve/ComparatorManagerImpl.java
+++ b/core/src/main/java/org/apache/jsieve/ComparatorManagerImpl.java
@@ -52,6 +52,8 @@ public class ComparatorManagerImpl implements 
ComparatorManager {
     }
     
     private final ConcurrentMap<String, String> classNameMap;
+    private final ImplementationCache<Comparator> implementations =
+            new ImplementationCache<>(Comparator.class, "Comparator", 
getClass().getClassLoader());
     /** 
      * The names of those comparisons for which <code>require</code> is not 
necessary before usage.
      * See <a href='http://tools.ietf.org/html/rfc5228#section-2.7.3'>RFC5228, 
2.7.3 Comparators</a>. 
@@ -99,18 +101,7 @@ public class ComparatorManagerImpl implements 
ComparatorManager {
      * @throws LookupException
      */
     public Class lookup(String name) throws LookupException {
-        Class comparatorClass;
-        try {
-            comparatorClass = getClass().getClassLoader().loadClass(
-                    getClassName(name));
-        } catch (ClassNotFoundException e) {
-            throw new LookupException("Comparator named '" + name
-                    + "' not found.");
-        }
-        if (!Comparator.class.isAssignableFrom(comparatorClass))
-            throw new LookupException("Class " + comparatorClass.getName()
-                    + " must implement " + Comparator.class.getName());
-        return comparatorClass;
+        return implementations.lookup(name, getClassName(name));
     }
 
     /**
@@ -125,13 +116,7 @@ public class ComparatorManagerImpl implements 
ComparatorManager {
      * @throws LookupException
      */
     public Comparator getComparator(String name) throws LookupException {
-        try {
-            return (Comparator) lookup(name).newInstance();
-        } catch (InstantiationException e) {
-            throw new LookupException(e.getMessage());
-        } catch (IllegalAccessException e) {
-            throw new LookupException(e.getMessage());
-        }
+        return implementations.newInstance(name, getClassName(name));
     }
 
     /**
diff --git a/core/src/main/java/org/apache/jsieve/ImplementationCache.java 
b/core/src/main/java/org/apache/jsieve/ImplementationCache.java
new file mode 100644
index 0000000..56c550a
--- /dev/null
+++ b/core/src/main/java/org/apache/jsieve/ImplementationCache.java
@@ -0,0 +1,124 @@
+/****************************************************************
+ * 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.jsieve;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.apache.jsieve.exception.LookupException;
+
+/**
+ * <p>
+ * Resolves the implementation classes a manager maps names to, and creates
+ * their instances. A class is loaded and its constructor resolved once per
+ * class name: evaluation asks for an instance for every command, test and
+ * comparison, and {@link ClassLoader#loadClass(String)} is costly even for a
+ * class already loaded.
+ * </p>
+ * <p>
+ * The cache is keyed by class name, not by the name it is mapped from, so a
+ * name mapped to another class resolves to that class. Failures are not
+ * cached.
+ * </p>
+ * <h4>Thread Safety</h4>
+ * <p>
+ * Instances may safely be accessed concurrently by multiple threads.
+ * </p>
+ */
+final class ImplementationCache<T> {
+
+    private final Class<T> type;
+    private final String kind;
+    private final ClassLoader classLoader;
+    private final ConcurrentMap<String, Constructor<? extends T>> constructors 
= new ConcurrentHashMap<>();
+
+    /**
+     * @param type the type implementations must have, not null
+     * @param kind what the names name, for messages, not null
+     * @param classLoader loads the classes, that of the manager so that a
+     *            subclass of it loads from its own loader, not null
+     */
+    ImplementationCache(Class<T> type, String kind, ClassLoader classLoader) {
+        this.type = type;
+        this.kind = kind;
+        this.classLoader = classLoader;
+    }
+
+    /**
+     * Answers the class named, after checking it has the expected type.
+     *
+     * @param name the name mapped to the class, for messages, not null
+     * @param className not null
+     * @throws LookupException when the class cannot be loaded or has not the
+     *             expected type
+     */
+    Class<? extends T> lookup(String name, String className) throws 
LookupException {
+        final Constructor<? extends T> constructor = 
constructors.get(className);
+        if (constructor != null) {
+            return constructor.getDeclaringClass();
+        }
+        return load(name, className);
+    }
+
+    /**
+     * Answers a new instance of the class named.
+     *
+     * @param name the name mapped to the class, for messages, not null
+     * @param className not null
+     * @throws LookupException when the class cannot be loaded or instantiated
+     */
+    T newInstance(String name, String className) throws LookupException {
+        Constructor<? extends T> constructor = constructors.get(className);
+        if (constructor == null) {
+            try {
+                constructor = load(name, className).getDeclaredConstructor();
+            } catch (NoSuchMethodException e) {
+                throw new LookupException(className + " has no constructor 
without argument");
+            }
+            final Constructor<? extends T> existing = 
constructors.putIfAbsent(className, constructor);
+            if (existing != null) {
+                constructor = existing;
+            }
+        }
+        try {
+            return constructor.newInstance();
+        } catch (InstantiationException | IllegalAccessException e) {
+            throw new LookupException(e.getMessage());
+        } catch (InvocationTargetException e) {
+            throw new LookupException(e.getCause().getMessage(), e.getCause());
+        }
+    }
+
+    private Class<? extends T> load(String name, String className) throws 
LookupException {
+        final Class<?> loaded;
+        try {
+            loaded = classLoader.loadClass(className);
+        } catch (ClassNotFoundException e) {
+            throw new LookupException(kind + " named '" + name + "' not 
found.");
+        }
+        if (!type.isAssignableFrom(loaded)) {
+            throw new LookupException("Class " + loaded.getName()
+                    + " must implement " + type.getName());
+        }
+        return loaded.asSubclass(type);
+    }
+}
diff --git a/core/src/main/java/org/apache/jsieve/TestManagerImpl.java 
b/core/src/main/java/org/apache/jsieve/TestManagerImpl.java
index 3022f43..a6fe45e 100644
--- a/core/src/main/java/org/apache/jsieve/TestManagerImpl.java
+++ b/core/src/main/java/org/apache/jsieve/TestManagerImpl.java
@@ -45,6 +45,8 @@ public class TestManagerImpl implements TestManager {
     }
 
     private final ConcurrentMap<String, String> classNameMap;
+    private final ImplementationCache<ExecutableTest> implementations =
+            new ImplementationCache<>(ExecutableTest.class, "Test", 
getClass().getClassLoader());
 
     /**
      * TestManager is instanciated with getInstance
@@ -65,18 +67,7 @@ public class TestManagerImpl implements TestManager {
      * @throws LookupException
      */
     public Class lookup(String name) throws LookupException {
-        Class testClass;
-
-        try {
-            testClass = getClass().getClassLoader().loadClass(
-                    getClassName(name));
-        } catch (ClassNotFoundException e) {
-            throw new LookupException("Test named '" + name + "' not found.");
-        }
-        if (!ExecutableTest.class.isAssignableFrom(testClass))
-            throw new LookupException("Class " + testClass.getName()
-                    + " must implement " + ExecutableTest.class.getName());
-        return testClass;
+        return implementations.lookup(name, getClassName(name));
     }
 
     /**
@@ -91,13 +82,7 @@ public class TestManagerImpl implements TestManager {
      * @throws LookupException
      */
     public ExecutableTest getTest(String name) throws LookupException {
-        try {
-            return (ExecutableTest) lookup(name).newInstance();
-        } catch (InstantiationException e) {
-            throw new LookupException(e.getMessage());
-        } catch (IllegalAccessException e) {
-            throw new LookupException(e.getMessage());
-        }
+        return implementations.newInstance(name, getClassName(name));
     }
 
     /**
diff --git a/core/src/test/java/org/apache/jsieve/ImplementationCacheTest.java 
b/core/src/test/java/org/apache/jsieve/ImplementationCacheTest.java
new file mode 100644
index 0000000..1b26c82
--- /dev/null
+++ b/core/src/test/java/org/apache/jsieve/ImplementationCacheTest.java
@@ -0,0 +1,119 @@
+/****************************************************************
+ * 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.jsieve;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.apache.jsieve.commands.Discard;
+import org.apache.jsieve.commands.Keep;
+import org.apache.jsieve.comparators.AsciiCasemap;
+import org.apache.jsieve.comparators.Octet;
+import org.apache.jsieve.exception.LookupException;
+import org.apache.jsieve.tests.False;
+import org.apache.jsieve.tests.True;
+import org.junit.Test;
+
+/**
+ * The managers resolve a class once, yet follow the changes of their
+ * mapping and hand out a new instance on each call.
+ */
+public class ImplementationCacheTest {
+
+    @Test
+    public void aComparatorShouldBeANewInstanceOnEachCall() throws Exception {
+        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
+        map.put("i;octet", Octet.class.getName());
+        ComparatorManagerImpl manager = new ComparatorManagerImpl(map);
+
+        assertThat(manager.getComparator("i;octet"))
+            .isInstanceOf(Octet.class)
+            .isNotSameAs(manager.getComparator("i;octet"));
+    }
+
+    @Test
+    public void aRemappedComparatorShouldResolveToItsNewClass() throws 
Exception {
+        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
+        map.put("i;octet", Octet.class.getName());
+        ComparatorManagerImpl manager = new ComparatorManagerImpl(map);
+        manager.getComparator("i;octet");
+
+        map.put("i;octet", AsciiCasemap.class.getName());
+
+        
assertThat(manager.getComparator("i;octet")).isInstanceOf(AsciiCasemap.class);
+        assertThat(manager.lookup("i;octet")).isEqualTo(AsciiCasemap.class);
+    }
+
+    @Test
+    public void aRemappedCommandShouldResolveToItsNewClass() throws Exception {
+        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
+        map.put("keep", Keep.class.getName());
+        CommandManagerImpl manager = new CommandManagerImpl(map);
+        assertThat(manager.getCommand("KEEP")).isInstanceOf(Keep.class);
+
+        map.put("keep", Discard.class.getName());
+
+        assertThat(manager.getCommand("keep")).isInstanceOf(Discard.class);
+    }
+
+    @Test
+    public void aRemappedTestShouldResolveToItsNewClass() throws Exception {
+        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
+        map.put("true", True.class.getName());
+        TestManagerImpl manager = new TestManagerImpl(map);
+        assertThat(manager.getTest("true")).isInstanceOf(True.class);
+
+        map.put("true", False.class.getName());
+
+        assertThat(manager.getTest("true")).isInstanceOf(False.class);
+    }
+
+    @Test
+    public void aMissingClassShouldFailOnEachCall() {
+        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
+        map.put("missing", "org.apache.jsieve.commands.Missing");
+        CommandManagerImpl manager = new CommandManagerImpl(map);
+
+        assertThatThrownBy(() -> manager.getCommand("missing"))
+            .isInstanceOf(LookupException.class)
+            .hasMessage("Command named 'missing' not found.");
+        assertThatThrownBy(() -> manager.getCommand("missing"))
+            .isInstanceOf(LookupException.class);
+        assertThat(manager.isCommandSupported("missing")).isFalse();
+
+        map.put("missing", Keep.class.getName());
+
+        assertThat(manager.isCommandSupported("missing")).isTrue();
+    }
+
+    @Test
+    public void aClassOfTheWrongTypeShouldBeRejected() {
+        ConcurrentMap<String, String> map = new ConcurrentHashMap<>();
+        map.put("keep", Keep.class.getName());
+        ComparatorManagerImpl manager = new ComparatorManagerImpl(map);
+
+        assertThatThrownBy(() -> manager.getComparator("keep"))
+            .isInstanceOf(LookupException.class)
+            .hasMessageContaining("must implement");
+    }
+}


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

Reply via email to