Skip to content

Commit 888cbd4

Browse files
mccullsmtoffl01
authored andcommitted
Expose Context.empty() as building block for creating custom root contexts (#8575)
This supports custom ContextManagers that want to define their own root context without needing to expose all the different context implementations. They can start with Context.empty() and add any elements they want, storing the final context as a constant so it can be supplied as Context.root()
1 parent 11b01da commit 888cbd4

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

components/context/src/main/java/datadog/context/Context.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,15 @@
3636
* @see ContextKey
3737
*/
3838
public interface Context {
39+
/**
40+
* Returns the empty context.
41+
*
42+
* @return the context containing no values at all.
43+
*/
44+
static Context empty() {
45+
return EmptyContext.INSTANCE;
46+
}
47+
3948
/**
4049
* Returns the root context.
4150
*

components/context/src/test/java/datadog/context/ContextTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package datadog.context;
22

3+
import static datadog.context.Context.empty;
34
import static datadog.context.Context.root;
45
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
56
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -21,6 +22,17 @@ class ContextTest {
2122
static final ContextKey<Float> FLOAT_KEY = ContextKey.named("float-key");
2223
static final ContextKey<Long> LONG_KEY = ContextKey.named("long-key");
2324

25+
@Test
26+
void testEmpty() {
27+
// Test empty is always the same
28+
Context empty = empty();
29+
assertEquals(empty, empty(), "Empty context should be consistent");
30+
// Test empty is not mutated
31+
String stringValue = "value";
32+
empty.with(STRING_KEY, stringValue);
33+
assertEquals(empty, empty(), "Empty context should be immutable");
34+
}
35+
2436
@Test
2537
void testRoot() {
2638
// Test root is always the same

0 commit comments

Comments
 (0)