From 3ab9ca687960d348a56364f1e2a8a7499b2d6f22 Mon Sep 17 00:00:00 2001 From: "James R. Perkins" Date: Thu, 8 Aug 2024 10:58:57 -0700 Subject: [PATCH] [92] Allow the ThreadContextMDCMap to work with both the JBoss Log Manager 3.0 and 2.1. Signed-off-by: James R. Perkins --- .../logmanager/log4j/ThreadContextMDCMap.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/jboss/logmanager/log4j/ThreadContextMDCMap.java b/src/main/java/org/jboss/logmanager/log4j/ThreadContextMDCMap.java index bd83469..07655eb 100644 --- a/src/main/java/org/jboss/logmanager/log4j/ThreadContextMDCMap.java +++ b/src/main/java/org/jboss/logmanager/log4j/ThreadContextMDCMap.java @@ -19,6 +19,9 @@ package org.jboss.logmanager.log4j; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; import java.util.Map; import org.apache.logging.log4j.spi.ThreadContextMap; @@ -30,6 +33,19 @@ * @author James R. Perkins */ public class ThreadContextMDCMap implements ThreadContextMap { + private static final MethodHandle IS_EMPTY; + + static { + // Use MDC.isEmpty() if it's available + MethodHandle handle = null; + try { + handle = MethodHandles.publicLookup() + .findStatic(MDC.class, "isEmpty", MethodType.methodType(boolean.class)); + } catch (NoSuchMethodException | IllegalAccessException ignore) { + } + IS_EMPTY = handle; + } + @Override public void clear() { MDC.clear(); @@ -58,7 +74,15 @@ public Map getImmutableMapOrNull() { @Override public boolean isEmpty() { - return MDC.isEmpty(); + if (IS_EMPTY != null) { + try { + return (boolean) IS_EMPTY.invoke(); + } catch (Throwable ignore) { + // Ignore and fall through to the fallback + } + } + // Fallback to a simple copy/isEmpty. This will not perform well, but also is likely not used much + return MDC.copy().isEmpty(); } @Override