0
# Context Management
1
2
Context management provides the foundational execution environment for polyglot programming. Contexts are isolated environments where guest language code executes with configurable security policies, resource limits, and access controls.
3
4
## Capabilities
5
6
### Context Creation
7
8
Create polyglot contexts for executing guest language code.
9
10
```java { .api }
11
public final class Context implements AutoCloseable {
12
public static Context create(String... permittedLanguages);
13
public static Context getCurrent();
14
}
15
```
16
17
**Usage:**
18
19
```java
20
// Create context for specific languages
21
Context jsContext = Context.create("js");
22
Context pythonContext = Context.create("python");
23
Context multiContext = Context.create("js", "python", "R");
24
25
// Get currently active context (from within guest code execution)
26
Context current = Context.getCurrent();
27
```
28
29
### Context Builder
30
31
Configure contexts with advanced options before creation.
32
33
```java { .api }
34
public static final class Context.Builder {
35
// Access control configuration
36
public Context.Builder allowHostAccess(HostAccess config);
37
public Context.Builder extendHostAccess(HostAccess defaultInitialValue, Consumer<HostAccess.Builder> setup);
38
public Context.Builder allowPolyglotAccess(PolyglotAccess config);
39
public Context.Builder allowCreateThread(boolean enabled);
40
public Context.Builder allowNativeAccess(boolean enabled);
41
public Context.Builder allowAllAccess(boolean enabled);
42
public Context.Builder allowHostClassLookup(Predicate<String> classFilter);
43
public Context.Builder allowHostClassLoading(boolean enabled);
44
public Context.Builder allowValueSharing(boolean enabled);
45
public Context.Builder allowInnerContextOptions(boolean enabled);
46
public Context.Builder allowCreateProcess(boolean enabled);
47
48
// I/O and environment configuration
49
public Context.Builder allowIO(IOAccess ioAccess);
50
public Context.Builder extendIO(IOAccess defaultInitialValue, Consumer<IOAccess.Builder> setup);
51
public Context.Builder allowEnvironmentAccess(EnvironmentAccess accessPolicy);
52
public Context.Builder environment(String name, String value);
53
public Context.Builder environment(Map<String, String> env);
54
public Context.Builder currentWorkingDirectory(Path workingDirectory);
55
56
// Stream configuration
57
public Context.Builder in(InputStream in);
58
public Context.Builder out(OutputStream out);
59
public Context.Builder err(OutputStream err);
60
61
// Engine and options
62
public Context.Builder engine(Engine engine);
63
public Context.Builder allowExperimentalOptions(boolean enabled);
64
public Context.Builder option(String key, String value);
65
public Context.Builder options(Map<String, String> options);
66
public Context.Builder arguments(String language, String[] args);
67
68
// Security and sandbox
69
public Context.Builder sandbox(SandboxPolicy policy);
70
public Context.Builder resourceLimits(ResourceLimits limits);
71
public Context.Builder useSystemExit(boolean enabled);
72
73
// Additional configuration
74
public Context.Builder hostClassLoader(ClassLoader classLoader);
75
public Context.Builder timeZone(ZoneId zone);
76
public Context.Builder logHandler(Handler logHandler);
77
public Context.Builder logHandler(OutputStream logOut);
78
public Context.Builder serverTransport(MessageTransport serverTransport);
79
public Context.Builder processHandler(ProcessHandler handler);
80
81
// Builder utilities
82
public Context.Builder apply(Consumer<Builder> action);
83
public Context build();
84
85
// Deprecated methods (for completeness)
86
@Deprecated public Context.Builder allowHostAccess(boolean enabled);
87
@Deprecated public Context.Builder hostClassFilter(Predicate<String> classFilter);
88
@Deprecated public Context.Builder allowIO(boolean enabled);
89
@Deprecated public Context.Builder fileSystem(FileSystem fileSystem);
90
}
91
```
92
93
**Usage:**
94
95
```java
96
Context context = Context.newBuilder("js")
97
.allowHostAccess(HostAccess.ALL)
98
.allowPolyglotAccess(PolyglotAccess.ALL)
99
.allowIO(IOAccess.ALL)
100
.sandbox(SandboxPolicy.CONSTRAINED)
101
.resourceLimits(ResourceLimits.newBuilder()
102
.statementLimit(10000, null)
103
.build())
104
.build();
105
```
106
107
### Code Execution
108
109
Execute and parse source code within contexts.
110
111
```java { .api }
112
public Value eval(String languageId, CharSequence source);
113
public Value eval(Source source);
114
public Value parse(String languageId, CharSequence source);
115
public Value parse(Source source);
116
```
117
118
**Usage:**
119
120
```java
121
try (Context context = Context.create("js")) {
122
// Direct execution
123
Value result = context.eval("js", "Math.sqrt(16)");
124
System.out.println(result.asDouble()); // 4.0
125
126
// Parse without execution
127
Value function = context.parse("js", "(x) => x * x");
128
Value squared = function.execute(5);
129
System.out.println(squared.asInt()); // 25
130
131
// Execute from Source
132
Source source = Source.create("js", "console.log('Hello from JS')");
133
context.eval(source);
134
}
135
```
136
137
### Bindings Access
138
139
Access and manipulate language-specific global bindings.
140
141
```java { .api }
142
public Value getBindings(String languageId);
143
```
144
145
**Usage:**
146
147
```java
148
try (Context context = Context.create("js")) {
149
Value bindings = context.getBindings("js");
150
151
// Set global variables
152
bindings.putMember("myVar", 42);
153
bindings.putMember("myFunction", new MyJavaFunction());
154
155
// Access global variables
156
context.eval("js", "myVar = myVar * 2");
157
Value result = bindings.getMember("myVar");
158
System.out.println(result.asInt()); // 84
159
}
160
```
161
162
### Value Conversion
163
164
Convert host values to polyglot values.
165
166
```java { .api }
167
public Value asValue(Object hostValue);
168
```
169
170
**Usage:**
171
172
```java
173
try (Context context = Context.create("js")) {
174
// Convert Java objects to polyglot values
175
List<String> javaList = Arrays.asList("a", "b", "c");
176
Value polyglotArray = context.asValue(javaList);
177
178
Map<String, Integer> javaMap = Map.of("x", 1, "y", 2);
179
Value polyglotObject = context.asValue(javaMap);
180
181
// Use in guest language
182
context.getBindings("js").putMember("data", polyglotArray);
183
context.eval("js", "console.log(data[0])"); // "a"
184
}
185
```
186
187
### Context Control
188
189
Control context execution and lifecycle.
190
191
```java { .api }
192
public void enter();
193
public void leave();
194
public boolean interrupt(Duration timeout);
195
public void resetLimits();
196
public void safepoint();
197
public void close();
198
public boolean isClosed();
199
public Engine getEngine();
200
```
201
202
**Usage:**
203
204
```java
205
Context context = Context.create("js");
206
207
// Manual context entering (advanced usage)
208
context.enter();
209
try {
210
// Context is active on current thread
211
Value result = context.eval("js", "42");
212
} finally {
213
context.leave();
214
}
215
216
// Interrupt long-running execution
217
CompletableFuture.runAsync(() -> {
218
context.eval("js", "while(true) {}"); // Infinite loop
219
});
220
221
// Interrupt after 5 seconds
222
boolean interrupted = context.interrupt(Duration.ofSeconds(5));
223
System.out.println("Interrupted: " + interrupted);
224
225
// Reset resource limits
226
context.resetLimits();
227
228
// Force a safepoint check
229
context.safepoint();
230
231
// Close context
232
context.close();
233
```
234
235
## Exception Handling
236
237
Contexts throw `PolyglotException` for guest language errors:
238
239
```java
240
try (Context context = Context.create("js")) {
241
context.eval("js", "throw new Error('Something went wrong')");
242
} catch (PolyglotException e) {
243
if (e.isGuestException()) {
244
System.out.println("Guest error: " + e.getMessage());
245
System.out.println("Location: " + e.getSourceLocation());
246
}
247
}
248
```
249
250
## Resource Management
251
252
Contexts implement `AutoCloseable` and should be used with try-with-resources:
253
254
```java
255
// Recommended pattern
256
try (Context context = Context.create("js")) {
257
// Use context
258
} // Automatically closed
259
260
// Or explicit closing
261
Context context = Context.create("js");
262
try {
263
// Use context
264
} finally {
265
context.close();
266
}
267
```
268
269
## Thread Safety
270
271
Contexts are **not thread-safe**. Each context should be used by only one thread at a time, or proper synchronization must be implemented. For multi-threaded usage, create separate contexts or use proper locking mechanisms.