[3.0] Clear ThreadLocal before injvm invoke (#9946)

This commit is contained in:
Albumen Kevin 2022-04-20 17:53:53 +08:00 committed by GitHub
parent 95378db853
commit f5e9d03663
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 1 deletions

View File

@ -55,6 +55,26 @@ public final class InternalThreadLocalMap {
return slowGet();
}
public static InternalThreadLocalMap getAndRemove() {
try {
Thread thread = Thread.currentThread();
if (thread instanceof InternalThread) {
return ((InternalThread) thread).threadLocalMap();
}
return slowThreadLocalMap.get();
} finally {
remove();
}
}
public static void set(InternalThreadLocalMap internalThreadLocalMap) {
Thread thread = Thread.currentThread();
if (thread instanceof InternalThread) {
((InternalThread) thread).setThreadLocalMap(internalThreadLocalMap);
}
slowThreadLocalMap.set(internalThreadLocalMap);
}
public static void remove() {
Thread thread = Thread.currentThread();
if (thread instanceof InternalThread) {

View File

@ -18,6 +18,7 @@ package org.apache.dubbo.rpc.protocol.injvm;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.threadlocal.InternalThreadLocalMap;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
@ -129,7 +130,14 @@ public class InjvmInvoker<T> extends AbstractInvoker<T> {
result.setExecutor(executor);
return result;
} else {
Result result = invoker.invoke(copiedInvocation);
Result result;
// clear thread local before child invocation, prevent context pollution
InternalThreadLocalMap originTL = InternalThreadLocalMap.getAndRemove();
try {
result = invoker.invoke(copiedInvocation);
} finally {
InternalThreadLocalMap.set(originTL);
}
if (result.hasException()) {
AsyncRpcResult rpcResult = AsyncRpcResult.newDefaultAsyncResult(result.getException(), copiedInvocation);
rpcResult.setObjectAttachments(new HashMap<>(result.getObjectAttachments()));