Skip to content
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

Minor improvements #217

Merged
merged 4 commits into from
Mar 22, 2021
Merged
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
9 changes: 6 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# Build / maven artifacts
*.class
# Build / Maven artifacts
target/
pom.xml.versionsBackup

Expand All @@ -11,10 +10,14 @@ pom.xml.versionsBackup
*.war
*.ear

# virtual machine crash logs, see https://www.java.com/en/download/help/error_hotspot.html
# Virtual machine crash logs, see https://www.java.com/en/download/help/error_hotspot.html
hs_err_pid*

# IntelliJ project files
.idea/
*.iml

# Eclipse project files
.settings/
.classpath
.project
1 change: 1 addition & 0 deletions .mvn/javadoc/package-list
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ nl.talsmasoftware.context.futures
nl.talsmasoftware.context.metrics
nl.talsmasoftware.context.locale
nl.talsmasoftware.context.mdc
nl.talsmasoftware.context.slf4j.mdc
Marcono1234 marked this conversation as resolved.
Show resolved Hide resolved
nl.talsmasoftware.context.opentracing
nl.talsmasoftware.context.servletrequest
nl.talsmasoftware.context.springsecurity
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
* and {@linkplain ContextManagers#onDeactivate(Class, Object, Object)} methods
* to notify the appropriate context observers.
*
* @param <T> type of the context value
* @author Sjoerd Talsma
*/
public interface ContextManager<T> {
Expand All @@ -46,7 +47,7 @@ public interface ContextManager<T> {
*
* @param value The value to initialize a new context for.
* @return The new <em>active</em> context containing the specified value
* which should be closed by the caller at the end of its lifecycle.
* which should be closed by the caller at the end of its lifecycle from the same thread.
*/
Context<T> initializeNewContext(T value);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public interface ContextSnapshot {
* Using the {@linkplain nl.talsmasoftware.context.executors.ContextAwareExecutorService ContextAwareExecutorService}
* is a safe way to propagate context snapshots without having to worry about closing them.
*
* @return A new reactivationcontext with the snapshot values that will be valid until closed
* @return A new reactivation context with the snapshot values that will be valid until closed
* (or new values are registered).
*/
Context<Void> reactivate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
package nl.talsmasoftware.context.clearable;

/**
* Interface that marks an to be 'clearable'.
* Interface that marks an object to be 'clearable'.
* <p>
* Context managers that support clearing the active context for the current thread
* should implement the {@link Clearable} interface.
Expand All @@ -26,6 +26,7 @@
* This operation is intended to only be used when re-using threads (e.g. when returning them to a thread-pool).
*
* @author Sjoerd Talsma
* @see ClearableContextManager
*/
public interface Clearable {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ protected CallMappingExecutorService(ExecutorService delegate) {
* @return The mapped callable object.
* @see #map(Callable)
*/
@Override
protected final <V> Callable<V> wrap(Callable<V> callable) {
return map(callable);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
* @author Sjoerd Talsma
*/
public class ContextAwareExecutorService extends CallMappingExecutorService {
private final Logger logger = Logger.getLogger(getClass().getName());
private static final Logger LOGGER = Logger.getLogger(ContextAwareExecutorService.class.getName());

public ContextAwareExecutorService(ExecutorService delegate) {
super(delegate);
Expand Down Expand Up @@ -77,12 +77,12 @@ public V call() throws Exception {
* @param context context to be closed
* @param exception exception if any occurred
*/
private void tryClose(Context<?> context, Exception exception) throws Exception {
private static void tryClose(Context<?> context, Exception exception) throws Exception {
if (context != null) try {
context.close();
} catch (RuntimeException closeEx) {
if (exception != null) {
logger.log(Level.WARNING, "Exception closing context after failed operation: " + closeEx.getMessage(), closeEx);
LOGGER.log(Level.WARNING, "Exception closing context after failed operation: " + closeEx.getMessage(), closeEx);
throw exception;
}
throw closeEx;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
* @author Sjoerd Talsma
*/
public abstract class AbstractThreadLocalContext<T> implements Context<T> {
private static final Logger LOGGER = Logger.getLogger(AbstractThreadLocalContext.class.getName());

private static final AtomicBoolean DEPRECATED_CONSTRUCTOR_WARNING = new AtomicBoolean(true);
/**
* The constant of ThreadLocal context instances per subclass name so different types don't get mixed.
Expand All @@ -43,7 +45,6 @@ public abstract class AbstractThreadLocalContext<T> implements Context<T> {

@SuppressWarnings("unchecked")
private final ThreadLocal<AbstractThreadLocalContext<T>> sharedThreadLocalContext = threadLocalInstanceOf((Class) getClass());
private final Logger logger = Logger.getLogger(getClass().getName());
private final AtomicBoolean closed = new AtomicBoolean(false);
private final Class<? extends ContextManager<? super T>> contextManagerType;

Expand Down Expand Up @@ -73,7 +74,7 @@ public abstract class AbstractThreadLocalContext<T> implements Context<T> {
@Deprecated
protected AbstractThreadLocalContext(T newValue) {
this(null, newValue);
logger.log(DEPRECATED_CONSTRUCTOR_WARNING.compareAndSet(true, false) ? Level.WARNING : Level.FINE,
LOGGER.log(DEPRECATED_CONSTRUCTOR_WARNING.compareAndSet(true, false) ? Level.WARNING : Level.FINE,
"Initialized new {0} without context manager type. " +
"This makes it impossible to register ContextObservers for it. " +
"Please fix {1} by specifying a ContextManager type " +
Expand All @@ -96,7 +97,7 @@ protected AbstractThreadLocalContext(Class<? extends ContextManager<? super T>>
this.parentContext = sharedThreadLocalContext.get();
this.value = newValue;
this.sharedThreadLocalContext.set(this);
logger.log(Level.FINEST, "Initialized new {0}.", this);
LOGGER.log(Level.FINEST, "Initialized new {0}.", this);
ContextManagers.onActivate(contextManagerType, value, parentContext == null ? null : parentContext.getValue());
}

Expand Down Expand Up @@ -147,7 +148,7 @@ public T getValue() {
public void close() {
final boolean observe = closed.compareAndSet(false, true);
final Context<T> restored = this.unwindIfNecessary(); // Remove this context created in the same thread.
logger.log(Level.FINEST, "Closed {0}.", this);
LOGGER.log(Level.FINEST, "Closed {0}.", this);
if (observe) {
ContextManagers.onDeactivate(contextManagerType, this.value, restored == null ? null : restored.getValue());
}
Expand All @@ -159,6 +160,7 @@ public void close() {
*
* @return String representing this context class and either the current value or the fact that it was closed.
*/
@Override
public String toString() {
return getClass().getSimpleName() + (isClosed() ? "{closed}" : "{value=" + value + '}');
}
Expand Down
7 changes: 3 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ private static final ExecutorService THREADPOOL =
The following `ThreadLocal`-based contexts are currently supported
out of the box by this context-propagation library:

- [Slf4J MDC (Mapped Diagnostic Context)][mdc propagation]
- [SLF4J MDC (Mapped Diagnostic Context)][slf4j mdc propagation]
- [OpenTracing Span contexts][opentracing span propagation]
- [Spring Security Context]
- [Locale context][locale context]
Expand Down Expand Up @@ -167,14 +167,13 @@ configure various timers in the global default metric registry of your applicati


[servletrequest propagation]: servletrequest-propagation
[mdc propagation]: slf4j-propagation
[slf4j mdc propagation]: slf4j-propagation
[locale context]: locale-context
[spring security context]: spring-security-context
[opentracing span propagation]: opentracing-span-propagation
[context propagation metrics]: context-propagation-metrics
[context propagation micrometer]: context-propagation-micrometer
[default constructor]: https://en.wikipedia.org/wiki/Nullary_constructor
[micrometer]: https://micrometer.io

[ContextAwareExecutorService]: https://javadoc.io/page/nl.talsmasoftware.context/context-propagation/latest/nl/talsmasoftware/context/executors/ContextAwareExecutorService.html
[ContextAwareExecutorService]: https://javadoc.io/doc/nl.talsmasoftware.context/context-propagation/latest/nl/talsmasoftware/context/executors/ContextAwareExecutorService.html
[ContextAwareCompletableFuture]: context-propagation-java8#contextawarecompletablefuture
6 changes: 3 additions & 3 deletions slf4j-propagation/README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
[![Maven Version][maven-img]][maven]

# Slf4J MDC propagation library
# SLF4J MDC propagation library

Adding the `slf4j-propagation` jar to your classpath
is all that is needed to let the [Mapped Diagnostic Context (MDC)][MDC]
from the [Simple Logging Facade for Java (SLF4J)][Slf4J]
is all that is needed to let the [Mapped Diagnostic Context (MDC)][mdc]
from the [Simple Logging Facade for Java (SLF4J)][slf4j]
be automatically included into the `ContextSnapshot`.

## How to use this library
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
import java.util.concurrent.atomic.AtomicBoolean;

/**
* Manager to propagate the {@link MDC} content from one thread to another.
* Manager to propagate the SLF4J {@link MDC} content from one thread to another.
* <p>
* As {@link MDC} already manages its own threadlocal state,
* As {@link MDC} already manages its own thread-local state,
* getting the active context is 100% delegated to the MDC.<br>
* This means that closing the resulting context from {@link #getActiveContext()} will have no side-effects,
* as it is not ours to manage.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/
/**
* Propagate the {@link org.slf4j.MDC Slf4J MDC} content from one thread to another.
* Propagate the {@linkplain org.slf4j.MDC SLF4J MDC} content from one thread to another.
*
* <p>
* This context manager maintains no threadlocal state of its own,
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
nl.talsmasoftware.context.slf4j.mdc.Slf4jMdcManager
nl.talsmasoftware.context.slf4j.mdc.Slf4jMdcManager
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ public void setupThreadpool() {
@AfterEach
public void shutdownThreadpool() {
threadpool.shutdown();
threadpool = null;
}

@BeforeEach
Expand Down Expand Up @@ -112,7 +111,6 @@ public void testSlf4jMdcContextToString() {

@Test
public void testClearActiveContexts() {
Slf4jMdcManager mgr = new Slf4jMdcManager();
MDC.put("dummy", "value");
// Test no-op for MdcManager
ContextManagers.clearActiveContexts();
Expand Down