unable to access context value.

112 views
Skip to first unread message

Vadiraj Jahagirdar

unread,
Jan 19, 2022, 6:17:49 AM1/19/22
to grpc.io
Hi,

I have following code: 

1. Context context = Context.current().withValue(Constant.FOO_CONTEXT_KEY, "Test Value");
2. String valueStr = Constant.FOO_CONTEXT_KEY.get();
3. System.out.println(valueStr);  //Returns null
4. context.run(() -> {
5.         System.out.println("Context Data is:" + Constant.FOO_CONTEXT_KEY.get()); //Gives "Test Value"
6.}

I am not able to understand why is null returned at line no 3, where as proper value is returned at line no 5.

Sergii Tkachenko

unread,
Jan 25, 2022, 1:48:47 PM1/25/22
to grpc.io
On line 3, you're inspecting a value of a context key, Context.Key<T>. On its own, the key is not bound to any specific context. Many different Context can use the same Context key, and each can set its own value for this key.
Line 5 is executed within the specific context you created (created on line 1, executed on line 4). Let's call it context A. This specific context has the key Constant.FOO_CONTEXT_KEY is set to the specific value: "Test Value". So line 5 returns the value of key Constant.FOO_CONTEXT_KEY as set in context A. 
Reply all
Reply to author
Forward
0 new messages