0
# Context Management
1
2
Context management provides the core functionality for creating, configuring, and managing Python execution environments within Java applications. Each context represents an isolated runtime with configurable security policies and resource limits.
3
4
## Capabilities
5
6
### Context Creation
7
8
Create execution contexts for Python with optional language restrictions and configuration.
9
10
```java { .api }
11
/**
12
* Creates a new context with the specified permitted languages
13
* @param permittedLanguages languages allowed in this context (e.g., "python")
14
* @return new Context instance
15
*/
16
public static Context create(String... permittedLanguages);
17
18
/**
19
* Creates a builder for advanced context configuration
20
* @param permittedLanguages languages allowed in this context
21
* @return Context.Builder for fluent configuration
22
*/
23
public static Context newBuilder(String... permittedLanguages);
24
```
25
26
**Usage Examples:**
27
28
```java
29
// Simple context creation
30
Context context = Context.create("python");
31
32
// Builder-based creation with configuration
33
Context context = Context.newBuilder("python")
34
.allowHostAccess(HostAccess.EXPLICIT)
35
.allowIO(IOAccess.NONE)
36
.sandbox(SandboxPolicy.CONSTRAINED)
37
.build();
38
```
39
40
### Code Evaluation
41
42
Execute Python code within the context and retrieve results.
43
44
```java { .api }
45
/**
46
* Evaluates source code in the specified language
47
* @param languageId the language identifier (use "python" for Python)
48
* @param source the source code to evaluate
49
* @return Value representing the evaluation result
50
* @throws PolyglotException if evaluation fails
51
*/
52
public Value eval(String languageId, CharSequence source);
53
54
/**
55
* Evaluates a Source object
56
* @param source the Source object to evaluate
57
* @return Value representing the evaluation result
58
* @throws PolyglotException if evaluation fails
59
*/
60
public Value eval(Source source);
61
```
62
63
**Usage Examples:**
64
65
```java
66
// Direct evaluation
67
Value result = context.eval("python", "2 + 3");
68
int sum = result.asInt(); // 5
69
70
// Multi-line Python code
71
String pythonCode = """
72
def fibonacci(n):
73
if n <= 1:
74
return n
75
return fibonacci(n-1) + fibonacci(n-2)
76
77
fibonacci(10)
78
""";
79
Value fibResult = context.eval("python", pythonCode);
80
int fib10 = fibResult.asInt(); // 55
81
82
// Using Source objects
83
Source source = Source.create("python", "import math; math.pi");
84
Value pi = context.eval(source);
85
double piValue = pi.asDouble(); // 3.141592653589793
86
```
87
88
### Bindings Access
89
90
Access and manipulate the global namespace of languages within the context.
91
92
```java { .api }
93
/**
94
* Gets the bindings object for a specific language
95
* @param languageId the language identifier
96
* @return Value representing the language's global bindings
97
*/
98
public Value getBindings(String languageId);
99
100
/**
101
* Gets the polyglot bindings shared across all languages
102
* @return Value representing shared polyglot bindings
103
*/
104
public Value getPolyglotBindings();
105
```
106
107
**Usage Examples:**
108
109
```java
110
// Access Python globals
111
context.eval("python", "x = 42; y = 'hello'");
112
Value pythonBindings = context.getBindings("python");
113
Value x = pythonBindings.getMember("x");
114
Value y = pythonBindings.getMember("y");
115
116
// Set values in Python namespace
117
pythonBindings.putMember("z", 100);
118
Value result = context.eval("python", "x + z"); // 142
119
120
// Access built-in functions
121
Value printFunction = pythonBindings.getMember("print");
122
printFunction.execute("Hello from Python!");
123
124
// Share data between languages via polyglot bindings
125
Value polyglotBindings = context.getPolyglotBindings();
126
polyglotBindings.putMember("shared_data", Arrays.asList(1, 2, 3));
127
context.eval("python", "shared_list = polyglot.import_value('shared_data')");
128
```
129
130
### Language Initialization
131
132
Force initialization of languages for performance optimization.
133
134
```java { .api }
135
/**
136
* Initializes the specified language in this context
137
* @param languageId the language to initialize
138
*/
139
public void initialize(String languageId);
140
```
141
142
**Usage Examples:**
143
144
```java
145
// Pre-initialize Python for faster first evaluation
146
context.initialize("python");
147
148
// Now evaluations will be faster
149
Value result = context.eval("python", "print('Hello, World!')");
150
```
151
152
### Context Lifecycle
153
154
Manage context lifecycle with proper resource cleanup and thread safety.
155
156
```java { .api }
157
/**
158
* Closes the context and releases all associated resources
159
* Waits for any currently executing code to complete
160
*/
161
public void close();
162
163
/**
164
* Closes the context with optional cancellation of executing code
165
* @param cancelIfExecuting if true, cancels any currently executing code
166
*/
167
public void close(boolean cancelIfExecuting);
168
169
/**
170
* Checks if the context has been closed
171
* @return true if the context is closed
172
*/
173
public boolean isClosed();
174
```
175
176
**Usage Examples:**
177
178
```java
179
// Try-with-resources (recommended)
180
try (Context context = Context.create("python")) {
181
Value result = context.eval("python", "2 + 2");
182
// Context automatically closed
183
}
184
185
// Manual lifecycle management
186
Context context = Context.create("python");
187
try {
188
// Use context
189
Value result = context.eval("python", "len([1, 2, 3])");
190
} finally {
191
context.close();
192
}
193
194
// Force cancellation of long-running code
195
context.close(true);
196
```
197
198
### Thread Safety
199
200
Manage context access across multiple threads safely.
201
202
```java { .api }
203
/**
204
* Enters the context for the current thread
205
* Must be paired with leave() call
206
*/
207
public void enter();
208
209
/**
210
* Leaves the context for the current thread
211
* Must be called after enter()
212
*/
213
public void leave();
214
```
215
216
**Usage Examples:**
217
218
```java
219
Context context = Context.create("python");
220
221
// Thread-safe context access
222
context.enter();
223
try {
224
Value result = context.eval("python", "import threading; threading.current_thread().name");
225
String threadName = result.asString();
226
} finally {
227
context.leave();
228
}
229
230
// Multiple thread access
231
ExecutorService executor = Executors.newFixedThreadPool(4);
232
for (int i = 0; i < 10; i++) {
233
int taskId = i;
234
executor.submit(() -> {
235
context.enter();
236
try {
237
Value result = context.eval("python", "task_id = " + taskId + "; task_id * 2");
238
System.out.println("Task " + taskId + " result: " + result.asInt());
239
} finally {
240
context.leave();
241
}
242
});
243
}
244
```
245
246
### Resource Management
247
248
Control resource usage and limits within the context.
249
250
```java { .api }
251
/**
252
* Resets all resource limits to their initial values
253
*/
254
public void resetLimits();
255
256
/**
257
* Triggers a safepoint, allowing for resource limit checks
258
* and potential interruption of executing code
259
*/
260
public void safepoint();
261
```
262
263
**Usage Examples:**
264
265
```java
266
// Context with resource limits
267
Context context = Context.newBuilder("python")
268
.resourceLimits(ResourceLimits.newBuilder()
269
.statementLimit(10000, null)
270
.timeLimit(Duration.ofSeconds(30))
271
.build())
272
.build();
273
274
try {
275
// Long-running operation
276
context.eval("python", "sum(range(1000000))");
277
} catch (PolyglotException e) {
278
if (e.isResourceExhausted()) {
279
System.out.println("Resource limit exceeded");
280
context.resetLimits(); // Reset for next operation
281
}
282
}
283
```
284
285
## Types
286
287
```java { .api }
288
/**
289
* Builder class for creating configured Context instances
290
*/
291
public static final class Context.Builder {
292
/**
293
* Sets the host access policy for this context
294
* @param config HostAccess configuration
295
* @return this builder
296
*/
297
public Builder allowHostAccess(HostAccess config);
298
299
/**
300
* Sets the polyglot access policy for inter-language evaluation
301
* @param config PolyglotAccess configuration
302
* @return this builder
303
*/
304
public Builder allowPolyglotAccess(PolyglotAccess config);
305
306
/**
307
* Sets the I/O access policy for file system operations
308
* @param config IOAccess configuration
309
* @return this builder
310
*/
311
public Builder allowIO(IOAccess config);
312
313
/**
314
* Sets the sandbox policy for security level
315
* @param policy SandboxPolicy level
316
* @return this builder
317
*/
318
public Builder sandbox(SandboxPolicy policy);
319
320
/**
321
* Sets the current working directory
322
* @param workingDirectory path to working directory
323
* @return this builder
324
*/
325
public Builder currentWorkingDirectory(Path workingDirectory);
326
327
/**
328
* Sets an engine option
329
* @param key option key
330
* @param value option value
331
* @return this builder
332
*/
333
public Builder option(String key, String value);
334
335
/**
336
* Sets multiple engine options
337
* @param options map of option key-value pairs
338
* @return this builder
339
*/
340
public Builder options(Map<String, String> options);
341
342
/**
343
* Sets input stream for guest language standard input
344
* @param in InputStream for stdin
345
* @return this builder
346
*/
347
public Builder in(InputStream in);
348
349
/**
350
* Sets output stream for guest language standard output
351
* @param out OutputStream for stdout
352
* @return this builder
353
*/
354
public Builder out(OutputStream out);
355
356
/**
357
* Sets error stream for guest language standard error
358
* @param err OutputStream for stderr
359
* @return this builder
360
*/
361
public Builder err(OutputStream err);
362
363
/**
364
* Builds the configured Context
365
* @return new Context instance
366
*/
367
public Context build();
368
}
369
```