Skip to content

Commit bfb152e

Browse files
committed
use one threadlocal in OpenTelemetryJsonRpcInvocationListener
1 parent 8536218 commit bfb152e

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

instrumentation/jsonrpc4j-1.3/library/src/main/java/io/opentelemetry/instrumentation/jsonrpc4j/v1_3/OpenTelemetryJsonRpcInvocationListener.java

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,33 @@
1515

1616
final class OpenTelemetryJsonRpcInvocationListener implements InvocationListener {
1717

18+
static class JsonRpcContext {
19+
private final Context context;
20+
private final Scope scope;
21+
private final JsonRpcServerRequest request;
22+
23+
JsonRpcContext(Context context, Scope scope, JsonRpcServerRequest request) {
24+
this.context = context;
25+
this.scope = scope;
26+
this.request = request;
27+
}
28+
29+
Context getContext() {
30+
return context;
31+
}
32+
33+
Scope getScope() {
34+
return scope;
35+
}
36+
37+
JsonRpcServerRequest getRequest() {
38+
return request;
39+
}
40+
}
41+
1842
private final Instrumenter<JsonRpcServerRequest, JsonRpcServerResponse> serverInstrumenter;
1943

20-
private static final ThreadLocal<Context> threadLocalContext = new ThreadLocal<>();
21-
private static final ThreadLocal<Scope> threadLocalScope = new ThreadLocal<>();
44+
private static final ThreadLocal<JsonRpcContext> threadLocalContext = new ThreadLocal<>();
2245

2346
public OpenTelemetryJsonRpcInvocationListener(
2447
Instrumenter<JsonRpcServerRequest, JsonRpcServerResponse> serverInstrumenter) {
@@ -40,8 +63,8 @@ public void willInvoke(Method method, List<JsonNode> arguments) {
4063
}
4164

4265
Context context = serverInstrumenter.start(parentContext, request);
43-
threadLocalContext.set(context);
44-
threadLocalScope.set(context.makeCurrent());
66+
Scope scope = context.makeCurrent();
67+
threadLocalContext.set(new JsonRpcContext(context, scope, request));
4568
}
4669

4770
/**
@@ -59,11 +82,10 @@ public void willInvoke(Method method, List<JsonNode> arguments) {
5982
@Override
6083
public void didInvoke(
6184
Method method, List<JsonNode> arguments, Object result, Throwable t, long duration) {
62-
JsonRpcServerRequest request = new JsonRpcServerRequest(method, arguments);
6385
JsonRpcServerResponse response = new JsonRpcServerResponse(method, arguments, result);
64-
threadLocalScope.get().close();
65-
serverInstrumenter.end(threadLocalContext.get(), request, response, t);
86+
threadLocalContext.get().getScope().close();
87+
serverInstrumenter.end(
88+
threadLocalContext.get().getContext(), threadLocalContext.get().getRequest(), response, t);
6689
threadLocalContext.remove();
67-
threadLocalScope.remove();
6890
}
6991
}

0 commit comments

Comments
 (0)