Skip to content

Commit

Permalink
Add span names cache (#4004)
Browse files Browse the repository at this point in the history
* Add span names cache

* Simplify
  • Loading branch information
trask authored Aug 30, 2021
1 parent 58d640a commit dc4e239
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package io.opentelemetry.instrumentation.api.caching;

import java.util.function.Function;
import org.checkerframework.checker.nullness.qual.Nullable;

/** A cache from keys to values. */
public interface Cache<K, V> {
Expand All @@ -25,6 +26,7 @@ static CacheBuilder newBuilder() {
* Returns the cached value associated with the provided {@code key} if present, or {@code null}
* otherwise.
*/
@Nullable
V get(K key);

/** Puts the {@code value} into the cache for the {@code key}. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,21 @@
package io.opentelemetry.instrumentation.api.tracer;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.checkerframework.checker.nullness.qual.Nullable;

public final class SpanNames {

private static final ClassValue<Map<String, String>> spanNameCaches =
new ClassValue<Map<String, String>>() {
@Override
protected Map<String, String> computeValue(Class<?> clazz) {
// the cache is naturally bounded by the number of methods in a class
return new ConcurrentHashMap<>();
}
};

/**
* This method is used to generate a span name based on a method. Anonymous classes are named
* based on their parent.
Expand All @@ -29,8 +41,16 @@ public static String fromMethod(Class<?> clazz, @Nullable Method method) {
* This method is used to generate a span name based on a method. Anonymous classes are named
* based on their parent.
*/
public static String fromMethod(Class<?> cl, String methodName) {
return ClassNames.simpleName(cl) + "." + methodName;
public static String fromMethod(Class<?> clazz, String methodName) {
Map<String, String> spanNameCache = spanNameCaches.get(clazz);
// not using computeIfAbsent, because it would require a capturing (allocating) lambda
String spanName = spanNameCache.get(methodName);
if (spanName != null) {
return spanName;
}
spanName = ClassNames.simpleName(clazz) + "." + methodName;
spanNameCache.put(methodName, spanName);
return spanName;
}

private SpanNames() {}
Expand Down

0 comments on commit dc4e239

Please sign in to comment.