Skip to content

Add support for thread context map propagation #2442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* 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 static org.junit.jupiter.api.Assertions.assertThrows;

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

/**
* A simple suite of tests for {@link ThreadContextMap} implementations.
*/
public abstract class ThreadContextMapSuite {
private static final String KEY = "key";

/**
* Checks if new threads either inherit or do not inherit the context data of the current thread.
*
* @param threadContext A {@link ThreadContextMap implementation}.
* @param key The key to use.
* @param expectedValue The expected value on a new thread.
*/
protected static void assertThreadContextValueOnANewThread(
final ThreadContextMap threadContext, final String key, final String expectedValue) {
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
assertThat(executorService.submit(() -> threadContext.get(key)))
.succeedsWithin(Duration.ofSeconds(1))
.isEqualTo(expectedValue);
} finally {
executorService.shutdown();
}
}

/**
* Ensures that {@code save/restore} works correctly on the current thread.
*/
protected static void assertContextDataCanBeSavedAndRestored(final ThreadContextMap threadContext) {
final String externalValue = "externalValue";
final String internalValue = "internalValue";
final RuntimeException throwable = new RuntimeException();
threadContext.put(KEY, externalValue);
final Object saved = threadContext.getContextData();
try {
threadContext.put(KEY, internalValue);
assertThat(threadContext.get(KEY)).isEqualTo(internalValue);
throw throwable;
} catch (final RuntimeException e) {
assertThat(e).isSameAs(throwable);
assertThat(threadContext.get(KEY)).isEqualTo(internalValue);
} finally {
threadContext.setContextData(saved);
}
assertThat(threadContext.get(KEY)).isEqualTo(externalValue);
}

/**
* Ensures that the context data obtained through {@link ThreadContextMap#getContextData} can be safely transferred to another
* thread.
*
* @param threadContext The {@link ThreadContextMap} to test.
*/
protected static void assertContextDataCanBeTransferred(final ThreadContextMap threadContext) {
final String mainThreadValue = "mainThreadValue";
final String newThreadValue = "newThreadValue";
final RuntimeException throwable = new RuntimeException();
threadContext.put(KEY, mainThreadValue);
final Object mainThreadSaved = threadContext.getContextData();
threadContext.remove(KEY);
// Move to new thread
final ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
assertThat(executorService.submit(() -> {
threadContext.put(KEY, newThreadValue);
final Object newThreadSaved = threadContext.setContextData(mainThreadSaved);
try {
assertThat(threadContext.get(KEY)).isEqualTo(mainThreadValue);
throw throwable;
} catch (final RuntimeException e) {
assertThat(e).isSameAs(throwable);
assertThat(threadContext.get(KEY)).isEqualTo(mainThreadValue);
} finally {
threadContext.setContextData(newThreadSaved);
}
assertThat(threadContext.get(KEY)).isEqualTo(newThreadValue);
}))
.succeedsWithin(Duration.ofSeconds(1));
} finally {
executorService.shutdown();
}
}

/**
* Ensures that the saved value is always not {@code null}, even if there are no context data.
* <p>
* This requirement allows third-party libraries to store the saved value as value of a map, even if the map
* does not allow nulls.
* </p>
*/
protected static void assertSavedValueNotNullIfMapEmpty(final ThreadContextMap threadContext) {
threadContext.clear();
final Object saved = threadContext.getContextData();
assertThat(saved).as("Saved empty context data.").isNotNull();
}

protected static void assertRestoreDoesNotAcceptNull(final ThreadContextMap threadContext) {
assertThrows(NullPointerException.class, () -> threadContext.setContextData(null));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* 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.
*/
/**
* Contains helper classes to blackbox test implementations of SPI interfaces.
* @since 2.24.0
*/
@Export
@Version("2.24.0")
package org.apache.logging.log4j.test.spi;

import org.osgi.annotation.bundle.Export;
import org.osgi.annotation.versioning.Version;
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,18 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.test.junit.Log4jStaticResources;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;

/**
* Tests {@link CloseableThreadContext}.
*
* @since 2.6
*/
@ResourceLock(value = Resources.SYSTEM_PROPERTIES, mode = ResourceAccessMode.READ)
@ResourceLock(Log4jStaticResources.THREAD_CONTEXT)
public class CloseableThreadContextTest {

private final String key = "key";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,61 +16,91 @@
*/
package org.apache.logging.log4j.spi;

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

import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import org.apache.logging.log4j.internal.map.StringArrayThreadContextMap;
import org.apache.logging.log4j.test.spi.ThreadContextMapSuite;
import org.apache.logging.log4j.util.Lazy;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

class ThreadContextMapTest {
@Execution(ExecutionMode.CONCURRENT)
class ThreadContextMapTest extends ThreadContextMapSuite {

private static final String KEY = "key";
private static final Lazy<PropertiesUtil> defaultMapProperties = Lazy.pure(() -> createMapProperties(false));
private static final Lazy<PropertiesUtil> inheritableMapProperties = Lazy.pure(() -> createMapProperties(true));

private static PropertiesUtil createMapProperties(final boolean inheritable) {
final Properties props = new Properties();
// By specifying all the possible properties, the resulting thread context maps do not depend on other
// property sources like Java system properties.
props.setProperty("log4j2.threadContextInitialCapacity", "16");
props.setProperty("log4j2.isThreadContextMapInheritable", inheritable ? "true" : "false");
return new PropertiesUtil(props);
}

static Stream<ThreadContextMap> defaultMaps() {
return Stream.of(
new DefaultThreadContextMap(),
new CopyOnWriteSortedArrayThreadContextMap(),
new GarbageFreeSortedArrayThreadContextMap());
new GarbageFreeSortedArrayThreadContextMap(),
new StringArrayThreadContextMap());
}

static Stream<ThreadContextMap> localMaps() {
return Stream.of(
new DefaultThreadContextMap(true, defaultMapProperties.get()),
new CopyOnWriteSortedArrayThreadContextMap(defaultMapProperties.get()),
new GarbageFreeSortedArrayThreadContextMap(defaultMapProperties.get()),
new StringArrayThreadContextMap());
}

static Stream<ThreadContextMap> inheritableMaps() {
final Properties props = new Properties();
props.setProperty("log4j2.isThreadContextMapInheritable", "true");
final PropertiesUtil util = new PropertiesUtil(props);
return Stream.of(
new DefaultThreadContextMap(true, util),
new CopyOnWriteSortedArrayThreadContextMap(util),
new GarbageFreeSortedArrayThreadContextMap(util));
new DefaultThreadContextMap(true, inheritableMapProperties.get()),
new CopyOnWriteSortedArrayThreadContextMap(inheritableMapProperties.get()),
new GarbageFreeSortedArrayThreadContextMap(inheritableMapProperties.get()));
}

@ParameterizedTest
@MethodSource("defaultMaps")
void threadLocalNotInheritableByDefault(final ThreadContextMap contextMap) {
contextMap.put(KEY, "threadLocalNotInheritableByDefault");
verifyThreadContextValueFromANewThread(contextMap, null);
void threadLocalNotInheritableByDefault(final ThreadContextMap threadContext) {
threadContext.put(KEY, "threadLocalNotInheritableByDefault");
assertThreadContextValueOnANewThread(threadContext, KEY, null);
}

@ParameterizedTest
@MethodSource("inheritableMaps")
void threadLocalInheritableIfConfigured(final ThreadContextMap contextMap) {
contextMap.put(KEY, "threadLocalInheritableIfConfigured");
verifyThreadContextValueFromANewThread(contextMap, "threadLocalInheritableIfConfigured");
void threadLocalInheritableIfConfigured(final ThreadContextMap threadContext) {
threadContext.put(KEY, "threadLocalInheritableIfConfigured");
assertThreadContextValueOnANewThread(threadContext, KEY, "threadLocalInheritableIfConfigured");
}

@ParameterizedTest
@MethodSource("localMaps")
void saveAndRestoreMap(final ThreadContextMap threadContext) {
assertContextDataCanBeSavedAndRestored(threadContext);
}

@ParameterizedTest
@MethodSource("localMaps")
void saveAndRestoreMapOnAnotherThread(final ThreadContextMap threadContext) {
assertContextDataCanBeTransferred(threadContext);
}

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();
}
@ParameterizedTest
@MethodSource("localMaps")
void savedValueNotNullIfMapEmpty(final ThreadContextMap threadContext) {
assertSavedValueNotNullIfMapEmpty(threadContext);
}

@ParameterizedTest
@MethodSource("localMaps")
void restoreDoesNotAcceptNull(final ThreadContextMap threadContext) {
assertRestoreDoesNotAcceptNull(threadContext);
}
}
12 changes: 11 additions & 1 deletion log4j-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,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 @@ -49,11 +51,19 @@

</properties>
<dependencies>

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

<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<scope>provided</scope>
</dependency>

</dependencies>
<build>
<plugins>
Expand Down
Loading