Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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.logging.log4j.test.spi;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.logging.log4j.spi.ThreadContextMap;

/**
* Provides a set of utility methods to test implementations of {@link ThreadContextMap}.
*/
public abstract class AbstractThreadContextMapTest {

private static final String KEY = "key";

/**
* Implementations SHOULD not propagate the context to newly created threads by default.
*
* @param contextMap A {@link ThreadContextMap implementation}.
*/
protected static void assertThreadLocalNotInheritable(final ThreadContextMap contextMap) {
contextMap.put(KEY, "threadLocalNotInheritableByDefault");
verifyThreadContextValueFromANewThread(contextMap, null);
}

/**
* Implementations MAY offer a configuration that propagates the context to newly created threads.
*
* @param contextMap A {@link ThreadContextMap implementation}.
*/
protected static void assertThreadLocalInheritable(final ThreadContextMap contextMap) {
contextMap.put(KEY, "threadLocalInheritableIfConfigured");
verifyThreadContextValueFromANewThread(contextMap, "threadLocalInheritableIfConfigured");
}

private static void verifyThreadContextValueFromANewThread(
final ThreadContextMap contextMap, final String expected) {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
assertThat(executorService.submit(() -> contextMap.get(KEY)))
.succeedsWithin(Duration.ofSeconds(1))
.isEqualTo(expected);
} finally {
executorService.shutdown();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,18 @@

import org.apache.logging.log4j.spi.DefaultThreadContextMap;
import org.apache.logging.log4j.test.ThreadContextUtilityClass;
import org.apache.logging.log4j.test.junit.InitializesThreadContext;
import org.apache.logging.log4j.test.junit.SetTestProperty;
import org.apache.logging.log4j.test.junit.UsingThreadContextMap;
import org.apache.logging.log4j.test.junit.UsingThreadContextStack;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.SetSystemProperty;

/**
* Tests {@link ThreadContext}.
*/
@SetTestProperty(key = DefaultThreadContextMap.INHERITABLE_MAP, value = "true")
@InitializesThreadContext
@UsingThreadContextMap
@UsingThreadContextStack
public class ThreadContextInheritanceTest {
Expand All @@ -63,31 +60,6 @@ public void testPush() {
assertEquals(ThreadContext.pop(), "Hello", "Incorrect simple stack value");
}

@Test
@SetSystemProperty(key = DefaultThreadContextMap.INHERITABLE_MAP, value = "true")
@InitializesThreadContext
public void testInheritanceSwitchedOn() throws Exception {
System.setProperty(DefaultThreadContextMap.INHERITABLE_MAP, "true");
try {
ThreadContext.clearMap();
ThreadContext.put("Greeting", "Hello");
StringBuilder sb = new StringBuilder();
TestThread thread = new TestThread(sb);
thread.start();
thread.join();
String str = sb.toString();
assertEquals("Hello", str, "Unexpected ThreadContext value. Expected Hello. Actual " + str);
sb = new StringBuilder();
thread = new TestThread(sb);
thread.start();
thread.join();
str = sb.toString();
assertEquals("Hello", str, "Unexpected ThreadContext value. Expected Hello. Actual " + str);
} finally {
System.clearProperty(DefaultThreadContextMap.INHERITABLE_MAP);
}
}

@Test
@Tag("performance")
public void perfTest() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,17 @@

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.logging.log4j.test.junit.UsingThreadContextMap;
import org.apache.logging.log4j.test.spi.AbstractThreadContextMapTest;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.junit.jupiter.api.Test;

/**
* Tests the {@code DefaultThreadContextMap} class.
*/
@UsingThreadContextMap
public class DefaultThreadContextMapTest {

@Test
public void testEqualsVsSameKind() {
final DefaultThreadContextMap map1 = createMap();
final DefaultThreadContextMap map2 = createMap();
assertEquals(map1, map1);
assertEquals(map2, map2);
assertEquals(map1, map2);
assertEquals(map2, map1);
}

@Test
public void testHashCodeVsSameKind() {
final DefaultThreadContextMap map1 = createMap();
final DefaultThreadContextMap map2 = createMap();
assertEquals(map1.hashCode(), map2.hashCode());
}
class DefaultThreadContextMapTest extends AbstractThreadContextMapTest {

@Test
public void testDoesNothingIfConstructedWithUseMapIsFalse() {
Expand Down Expand Up @@ -214,4 +200,17 @@ public void testToStringShowsMapContext() {
map.put("key2", "value2");
assertEquals("{key2=value2}", map.toString());
}

@Test
void threadLocalNotInheritableByDefault() {
assertThreadLocalNotInheritable(new DefaultThreadContextMap());
}

@Test
void threadLocalInheritableIfConfigured() {
final Properties props = new Properties();
props.setProperty("log4j2.isThreadContextMapInheritable", "true");
final PropertiesUtil util = new PropertiesUtil(props);
assertThreadLocalInheritable(new DefaultThreadContextMap(true, util));
}
}
11 changes: 10 additions & 1 deletion log4j-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@
<bnd-module-name>org.apache.logging.log4j</bnd-module-name>
<bnd-extra-package-options>
<!-- Not exported by most OSGi system bundles, hence we use the system classloader to load `sun.reflect.Reflection` -->
!sun.reflect
!sun.reflect,
<!-- Annotations only -->
org.jspecify.*;resolution:=optional
</bnd-extra-package-options>
<bnd-extra-module-options>
<!-- Used in StringBuilders through reflection -->
Expand All @@ -57,6 +59,13 @@

</properties>
<dependencies>

<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,12 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.internal.map.StringArrayThreadContextMap;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.spi.CleanableThreadContextMap;
import org.apache.logging.log4j.spi.DefaultThreadContextMap;
import org.apache.logging.log4j.spi.DefaultThreadContextStack;
import org.apache.logging.log4j.spi.MutableThreadContextStack;
import org.apache.logging.log4j.spi.ReadOnlyThreadContextMap;
import org.apache.logging.log4j.spi.ThreadContextMap;
import org.apache.logging.log4j.spi.ThreadContextMap2;
import org.apache.logging.log4j.spi.ThreadContextMapFactory;
import org.apache.logging.log4j.spi.ThreadContextStack;
import org.apache.logging.log4j.util.PropertiesUtil;
Expand Down Expand Up @@ -268,21 +265,11 @@ public static void putIfNull(final String key, final String value) {
*
* <p>If the current thread does not have a context map it is
* created as a side effect.</p>
* @param m The map.
* @param map The map.
* @since 2.7
*/
public static void putAll(final Map<String, String> m) {
if (contextMap instanceof ThreadContextMap2) {
((ThreadContextMap2) contextMap).putAll(m);
} else if (contextMap instanceof DefaultThreadContextMap) {
((DefaultThreadContextMap) contextMap).putAll(m);
} else if (contextMap instanceof StringArrayThreadContextMap) {
((StringArrayThreadContextMap) contextMap).putAll(m);
} else {
for (final Map.Entry<String, String> entry : m.entrySet()) {
contextMap.put(entry.getKey(), entry.getValue());
}
}
public static void putAll(final Map<String, String> map) {
contextMap.putAll(map);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please maintain separate if/else branches for the most common instance types, as in the previous version. This avoids virtual method lookups for those types.

}

/**
Expand Down Expand Up @@ -316,17 +303,7 @@ public static void remove(final String key) {
* @since 2.8
*/
public static void removeAll(final Iterable<String> keys) {
if (contextMap instanceof CleanableThreadContextMap) {
((CleanableThreadContextMap) contextMap).removeAll(keys);
} else if (contextMap instanceof DefaultThreadContextMap) {
((DefaultThreadContextMap) contextMap).removeAll(keys);
} else if (contextMap instanceof StringArrayThreadContextMap) {
((StringArrayThreadContextMap) contextMap).removeAll(keys);
} else {
for (final String key : keys) {
contextMap.remove(key);
}
}
contextMap.removeAll(keys);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please maintain separate if/else branches for the most common instance types, as in the previous version. This avoids virtual method lookups for those types.

}

/**
Expand Down
Loading