Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes thread safety issue in Tag.tag #1434

Merged
merged 1 commit into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion brave/src/main/java/brave/Tag.java
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ final void tag(Object span, I input, @Nullable TraceContext context) {
if (span instanceof SpanCustomizer) {
((SpanCustomizer) span).tag(key, value);
} else if (span instanceof MutableSpan) {
((MutableSpan) span).tag(key, value);
MutableSpan mSpan = (MutableSpan) span;
synchronized (mSpan) {
mSpan.tag(key, value);
}
}
}

Expand Down
24 changes: 24 additions & 0 deletions brave/src/test/java/brave/TagTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

import brave.handler.MutableSpan;
import brave.propagation.TraceContext;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -257,6 +260,27 @@ class TagTest {
assertThat(mutableSpan).isEqualTo(expected);
}

@Test
public void tag_mutableSpan_threadSafe() throws InterruptedException {
int numThreads = 1000;
ExecutorService service = Executors.newFixedThreadPool(numThreads);
try {
for (int i = 0; i < numThreads; i++) {
String val = String.valueOf(i);
Tag<Object> tag = new Tag<Object>("key" + i) {
@Override protected String parseValue(Object input, TraceContext context) {
return val;
}
};
service.submit(() -> tag.tag(input, context, mutableSpan));
}
} finally {
service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
}
assertThat(mutableSpan.tagCount()).isEqualTo(numThreads);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you take out synchronized, this test fails

}

@Test void tag_mutableSpan_nullContext() {
when(parseValue.apply(eq(input), isNull())).thenReturn("value");

Expand Down