Skip to content

Commit 6a00796

Browse files
authored
XCOMMONS-3256: Cleaning the Velocity introspection cache is expensive (#1232)
* Store the field as a static field to avoid the runtime overhead of repeatedly getting the field.
1 parent f5b64b8 commit 6a00796

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/internal/InternalVelocityEngine.java

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.io.Reader;
2323
import java.io.StringReader;
2424
import java.io.Writer;
25+
import java.lang.reflect.Field;
2526
import java.util.Deque;
2627
import java.util.LinkedList;
2728
import java.util.List;
@@ -60,6 +61,13 @@
6061
@InstantiationStrategy(ComponentInstantiationStrategy.PER_LOOKUP)
6162
public class InternalVelocityEngine implements VelocityEngine
6263
{
64+
/**
65+
* The field that stores the introspection cache. This field is accessed once here as it causes several exceptions
66+
* to be thrown internally until the field is found, which is expensive.
67+
*/
68+
private static final Field INTROSPECTION_CACHE_FIELD =
69+
FieldUtils.getField(VelocityContext.class, "introspectionCache", true);
70+
6371
private static final String ECONTEXT_TEMPLATES = "velocity.templates";
6472

6573
private class TemplateEntry
@@ -245,8 +253,14 @@ private void cleanIntrospectionCache(Context context)
245253
{
246254
if (context != null) {
247255
try {
248-
Map introspectionCache = (Map) FieldUtils.readField(context, "introspectionCache", true);
249-
introspectionCache.clear();
256+
if (INTROSPECTION_CACHE_FIELD != null) {
257+
Map<?, ?> introspectionCache = (Map<?, ?>) INTROSPECTION_CACHE_FIELD.get(context);
258+
introspectionCache.clear();
259+
} else {
260+
this.logger.warn(
261+
"Failed to clean the Velocity context introspection cache because the introspection cache "
262+
+ "field could not be found.");
263+
}
250264
} catch (IllegalAccessException e) {
251265
this.logger.warn("Failed to clean the Velocity context introspection cache. Root error: [{}]",
252266
ExceptionUtils.getRootCauseMessage(e));

0 commit comments

Comments
 (0)