Skip to content

Commit

Permalink
Copying MDC context in every async calls that go through ThreadLocalP…
Browse files Browse the repository at this point in the history
…ropagateContext.wrap method
  • Loading branch information
sunix committed Feb 6, 2018
1 parent fe30c9a commit e7a85a4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,35 @@
*/
package org.eclipse.che.commons.lang.concurrent;

import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.MDC;

/** @author andrew00x */
class CopyThreadLocalCallable<T> implements Callable<T> {
private final Callable<? extends T> wrapped;
private final ThreadLocalPropagateContext.ThreadLocalState threadLocalState;
private Map<String, String> currentMdcState;

CopyThreadLocalCallable(Callable<? extends T> wrapped) {
// Called from main thread. Copy the current values of all the ThreadLocal variables which
// registered in ThreadLocalPropagateContext.
this.wrapped = wrapped;
this.threadLocalState = ThreadLocalPropagateContext.currentThreadState();
this.currentMdcState = MDC.getCopyOfContextMap();
}

@Override
public T call() throws Exception {
try {
threadLocalState.propagate();
if (currentMdcState != null) {
MDC.setContextMap(currentMdcState);
}
return wrapped.call();
} finally {
threadLocalState.cleanup();
MDC.clear();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,34 @@
*/
package org.eclipse.che.commons.lang.concurrent;

import java.util.Map;
import org.slf4j.MDC;

/** @author andrew00x */
class CopyThreadLocalRunnable implements Runnable {
private final Runnable wrapped;
private final ThreadLocalPropagateContext.ThreadLocalState threadLocalState;
private Map<String, String> currentMdcState;

CopyThreadLocalRunnable(Runnable wrapped) {
// Called from main thread. Copy the current values of all the ThreadLocal variables which
// registered in ThreadLocalPropagateContext.
this.wrapped = wrapped;
this.threadLocalState = ThreadLocalPropagateContext.currentThreadState();
this.currentMdcState = MDC.getCopyOfContextMap();
}

@Override
public void run() {
try {
threadLocalState.propagate();
if (currentMdcState != null) {
MDC.setContextMap(currentMdcState);
}
wrapped.run();
} finally {
threadLocalState.cleanup();
MDC.clear();
}
}

Expand Down

0 comments on commit e7a85a4

Please sign in to comment.