-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstrumenterContext.java
65 lines (56 loc) · 1.94 KB
/
InstrumenterContext.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.instrumentation.api.internal;
import io.opentelemetry.instrumentation.api.instrumenter.AttributesExtractor;
import io.opentelemetry.instrumentation.api.instrumenter.Instrumenter;
import io.opentelemetry.instrumentation.api.instrumenter.SpanNameExtractor;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Helper class for sharing computed values between different {@link AttributesExtractor}s and
* {@link SpanNameExtractor} called in the start phase of the {@link Instrumenter}.
*
* <p>This class is internal and is hence not for public use. Its APIs are unstable and can change
* at any time.
*/
public final class InstrumenterContext {
private static final ThreadLocal<InstrumenterContext> instrumenterContext = new ThreadLocal<>();
private final Map<String, Object> map = new HashMap<>();
private int useCount;
private InstrumenterContext() {}
@SuppressWarnings("unchecked")
public static <T> T computeIfAbsent(String key, Function<String, T> function) {
InstrumenterContext context = instrumenterContext.get();
if (context == null) {
return function.apply(key);
}
return (T) context.map.computeIfAbsent(key, function);
}
// visible for testing
static Map<String, Object> get() {
return instrumenterContext.get().map;
}
public static boolean isActive() {
return instrumenterContext.get() != null;
}
public static <T> T withContext(Supplier<T> action) {
InstrumenterContext context = instrumenterContext.get();
if (context == null) {
context = new InstrumenterContext();
instrumenterContext.set(context);
}
context.useCount++;
try {
return action.get();
} finally {
context.useCount--;
if (context.useCount == 0) {
instrumenterContext.remove();
}
}
}
}