Skip to content

Commit 7381fd1

Browse files
authored
Merge pull request #3 from Nepxion/zifeihan
Avoid calling in the same thread
2 parents 9bd50e8 + 512d4eb commit 7381fd1

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

discovery-agent-starter/src/main/java/com/nepxion/discovery/agent/async/AsyncContext.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,21 @@
1212
public class AsyncContext {
1313
private Object[] objects;
1414

15+
/**
16+
* Record the original thread and compare it with the thread that called runnable/callable.
17+
*/
18+
private Thread originThread;
19+
1520
public AsyncContext(Object[] objects) {
1621
this.objects = objects;
22+
this.originThread = Thread.currentThread();
1723
}
1824

1925
public Object[] getObjects() {
2026
return objects;
2127
}
28+
29+
public Thread getOriginThread() {
30+
return originThread;
31+
}
2232
}

discovery-agent-starter/src/main/java/com/nepxion/discovery/agent/plugin/spring/async/WrapCallable.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ public WrapCallable(Callable<T> callable) {
2727

2828
@Override
2929
public T call() throws Exception {
30+
31+
//Avoid calling in the same thread.
32+
if (asyncContext.getOriginThread().equals(Thread.currentThread())) {
33+
return callable.call();
34+
}
35+
36+
//Call the original method and copy some objects held by ThreadLocal.
3037
Object[] objects = asyncContext.getObjects();
3138
ThreadLocalCopier.before(objects);
3239
try {

discovery-agent-starter/src/main/java/com/nepxion/discovery/agent/plugin/thread/interceptor/ThreadCallInterceptor.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,26 @@ public static void before(Object object) {
2121
if (null == asyncContext) {
2222
return;
2323
}
24+
//Avoid calling in the same thread.
25+
if (asyncContext.getOriginThread().equals(Thread.currentThread())) {
26+
return;
27+
}
2428
Object[] objects = asyncContext.getObjects();
2529
ThreadLocalCopier.before(objects);
2630
}
2731
}
2832

2933
public static void after(Object object) {
3034
if (object instanceof AsyncContextAccessor) {
35+
AsyncContextAccessor asyncContextAccessor = (AsyncContextAccessor) object;
36+
AsyncContext asyncContext = asyncContextAccessor.getAsyncContext();
37+
if (null == asyncContext) {
38+
return;
39+
}
40+
//Avoid calling in the same thread.
41+
if (asyncContext.getOriginThread().equals(Thread.currentThread())) {
42+
return;
43+
}
3144
ThreadLocalCopier.after();
3245
}
3346
}

0 commit comments

Comments
 (0)