Skip to content

Commit 0d07543

Browse files
Make SpanContext truly immutable. (#165)
1 parent 387a6ac commit 0d07543

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

common/src/main/java/com/lightstep/tracer/shared/SpanContext.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,10 @@ Map<String, String> getBaggage() {
9090
}
9191

9292
SpanContext withBaggageItem(String key, String value) {
93-
// This is really a "set" not a "with" but keeping as is to preserve behavior.
94-
this.baggage.put(key, value);
95-
return new SpanContext(this.getTraceId(), this.getSpanId(), this.baggage, this.foreignTraceId);
93+
// Do NOT modify our own baggage, as SpanContext is expected to be immutable.
94+
Map<String, String> newBaggage = new HashMap<String, String>(this.baggage);
95+
newBaggage.put(key, value);
96+
return new SpanContext(this.getTraceId(), this.getSpanId(), newBaggage, this.foreignTraceId);
9697
}
9798

9899
@Override

common/src/test/java/com/lightstep/tracer/shared/SpanTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,15 @@ public void setup() {
4949
undertest = new Span(abstractTracer, spanContext, grpcSpan, 0L);
5050
}
5151

52+
@Test
53+
public void testContext_isImmutable() {
54+
undertest.setBaggageItem("foo", "bar");
55+
SpanContext anotherSpanContext = undertest.context();
56+
assertNull(spanContext.getBaggageItem("foo"));
57+
assertNotNull(anotherSpanContext.getBaggageItem("foo"));
58+
assertNotNull(undertest.getBaggageItem("foo"));
59+
}
60+
5261
@Test
5362
public void testContext() {
5463
assertSame(spanContext, undertest.context());

0 commit comments

Comments
 (0)