org.macrocloud.kernel.context.CallableWrapper Maven / Gradle / Ivy
package org.macrocloud.kernel.context;
import org.slf4j.MDC;
import org.macrocloud.kernel.toolkit.utils.ThreadLocalUtil;
import org.springframework.lang.Nullable;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* 多线程中传递 context 和 mdc
*
* @author macro
*/
public class CallableWrapper implements Callable {
private final Callable delegate;
private final Map tlMap;
/**
* logback 下有可能为 null
*/
@Nullable
private final Map mdcMap;
public CallableWrapper(Callable callable) {
this.delegate = callable;
this.tlMap = ThreadLocalUtil.getAll();
this.mdcMap = MDC.getCopyOfContextMap();
}
@Override
public V call() throws Exception {
if (!tlMap.isEmpty()) {
ThreadLocalUtil.put(tlMap);
}
if (mdcMap != null && !mdcMap.isEmpty()) {
MDC.setContextMap(mdcMap);
}
try {
return delegate.call();
} finally {
tlMap.clear();
if (mdcMap != null) {
mdcMap.clear();
}
ThreadLocalUtil.clear();
MDC.clear();
}
}
}