0
# gRPC Context
1
2
gRPC Context is a Java library that provides a context propagation mechanism for carrying scoped values across API boundaries and between threads. It enables secure transmission of security principals, credentials, and distributed tracing information through immutable Context objects with automatic inheritance, cancellation propagation, and timeout-based automatic cancellation.
3
4
## Package Information
5
6
- **Package Name**: io.grpc:grpc-context
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>io.grpc</groupId>
13
<artifactId>grpc-context</artifactId>
14
<version>1.73.0</version>
15
</dependency>
16
```
17
18
## Core Imports
19
20
```java
21
import io.grpc.Context;
22
import io.grpc.Deadline;
23
```
24
25
## Basic Usage
26
27
```java
28
import io.grpc.Context;
29
import java.util.concurrent.TimeUnit;
30
31
// Create a context key
32
Context.Key<String> USER_ID_KEY = Context.key("userId");
33
34
// Set a value in the current context
35
Context withUser = Context.current().withValue(USER_ID_KEY, "user123");
36
37
// Run code within the context scope
38
withUser.run(() -> {
39
String userId = USER_ID_KEY.get(); // "user123"
40
processUserRequest(userId);
41
});
42
43
// Create a cancellable context with timeout
44
try (Context.CancellableContext withTimeout = Context.current()
45
.withDeadlineAfter(5, TimeUnit.SECONDS, scheduler)) {
46
47
Context toRestore = withTimeout.attach();
48
try {
49
// Long-running operation that will be cancelled after 5 seconds
50
performLongRunningTask();
51
} finally {
52
withTimeout.detach(toRestore);
53
}
54
}
55
```
56
57
## Architecture
58
59
gRPC Context is built around several key components:
60
61
- **Context Objects**: Immutable containers for scoped values that inherit from parent contexts
62
- **Storage System**: Pluggable storage mechanism with default ThreadLocal-based implementation
63
- **Key System**: Type-safe keys using reference equality for accessing context values
64
- **Cancellation Framework**: Hierarchical cancellation with listener notification and cause tracking
65
- **Deadline Management**: Absolute time-based automatic cancellation with timeout conversion
66
- **Execution Wrapping**: Utilities to propagate context across thread boundaries and async operations
67
68
## Capabilities
69
70
### Context Management
71
72
Core context creation, attachment, and value propagation functionality. Essential for maintaining scoped state across API boundaries and thread switches.
73
74
```java { .api }
75
public static final Context ROOT;
76
public static Context current();
77
public static <T> Context.Key<T> key(String debugString);
78
public static <T> Context.Key<T> keyWithDefault(String debugString, T defaultValue);
79
80
public <V> Context withValue(Context.Key<V> key, V value);
81
public Context fork();
82
public Context attach();
83
public void detach(Context toAttach);
84
```
85
86
[Context Management](./context-management.md)
87
88
### Cancellation System
89
90
Cancellable contexts with hierarchical cancellation propagation, listener notification, and cause tracking for managing the lifecycle of operations.
91
92
```java { .api }
93
public Context.CancellableContext withCancellation();
94
public boolean isCancelled();
95
public Throwable cancellationCause();
96
public void addListener(Context.CancellationListener listener, Executor executor);
97
98
public interface CancellationListener {
99
void cancelled(Context context);
100
}
101
102
public static final class CancellableContext extends Context implements Closeable {
103
public boolean cancel(Throwable cause);
104
public void close();
105
}
106
```
107
108
[Cancellation System](./cancellation-system.md)
109
110
### Deadline Management
111
112
Absolute time-based deadline management with automatic cancellation and timeout conversion capabilities for time-bounded operations.
113
114
```java { .api }
115
public Context.CancellableContext withDeadline(Deadline deadline, ScheduledExecutorService scheduler);
116
public Context.CancellableContext withDeadlineAfter(long duration, TimeUnit unit, ScheduledExecutorService scheduler);
117
public Deadline getDeadline();
118
119
public static Deadline after(long duration, TimeUnit units);
120
public boolean isExpired();
121
public long timeRemaining(TimeUnit unit);
122
```
123
124
[Deadline Management](./deadline-management.md)
125
126
### Execution Utilities
127
128
Utilities for wrapping Runnables, Callables, and Executors to automatically propagate context across thread boundaries and asynchronous operations.
129
130
```java { .api }
131
public void run(Runnable r);
132
public <V> V call(Callable<V> c) throws Exception;
133
public Runnable wrap(Runnable r);
134
public <C> Callable<C> wrap(Callable<C> c);
135
public Executor fixedContextExecutor(Executor e);
136
public static Executor currentContextExecutor(Executor e);
137
```
138
139
[Execution Utilities](./execution-utilities.md)
140
141
## Types
142
143
```java { .api }
144
public static final class Key<T> {
145
public T get();
146
public T get(Context context);
147
public String toString();
148
}
149
150
public abstract static class Storage {
151
public abstract Context doAttach(Context toAttach);
152
public abstract void detach(Context toDetach, Context toRestore);
153
public abstract Context current();
154
}
155
156
public abstract static class Ticker {
157
public abstract long nanoTime();
158
}
159
```