Skip to content

Commit

Permalink
[92] Allow the ThreadContextMDCMap to work with both the JBoss Log Ma…
Browse files Browse the repository at this point in the history
…nager 3.0 and 2.1.

Signed-off-by: James R. Perkins <[email protected]>
  • Loading branch information
jamezp committed Aug 8, 2024
1 parent 1a30abb commit 3ab9ca6
Showing 1 changed file with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -30,6 +33,19 @@
* @author <a href="mailto:[email protected]">James R. Perkins</a>
*/
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();
Expand Down Expand Up @@ -58,7 +74,15 @@ public Map<String, String> 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
Expand Down

0 comments on commit 3ab9ca6

Please sign in to comment.