0
# Context and Engine Management
1
2
Context and Engine are the foundational components for managing polyglot execution environments. The Context represents an isolated execution environment for guest languages, while the Engine provides a shared runtime that manages multiple contexts efficiently.
3
4
## Context Lifecycle
5
6
The Context class manages the execution environment for one or more guest languages with complete isolation and security controls.
7
8
### Context Creation
9
10
```java { .api }
11
// Simple context creation
12
public static Context create(String... permittedLanguages);
13
14
// Builder pattern for advanced configuration
15
public static Context.Builder newBuilder(String... permittedLanguages);
16
17
// Get current context (if any)
18
public static Context getCurrent();
19
```
20
21
**Usage Examples:**
22
23
```java
24
// Single language context
25
try (Context context = Context.create("js")) {
26
// JavaScript execution environment
27
}
28
29
// Multi-language context
30
try (Context context = Context.create("js", "python", "ruby")) {
31
// All three languages available
32
}
33
34
// Builder pattern with configuration
35
Context context = Context.newBuilder("js")
36
.allowHostAccess(HostAccess.EXPLICIT)
37
.allowPolyglotAccess(PolyglotAccess.NONE)
38
.sandbox(SandboxPolicy.CONSTRAINED)
39
.build();
40
```
41
42
### Context Builder Configuration
43
44
The Context.Builder provides comprehensive configuration options for security, I/O, and runtime behavior.
45
46
```java { .api }
47
public static final class Context.Builder {
48
// Engine configuration
49
public Context.Builder engine(Engine engine);
50
51
// I/O stream configuration
52
public Context.Builder out(OutputStream out);
53
public Context.Builder err(OutputStream err);
54
public Context.Builder in(InputStream in);
55
56
// Access policy configuration
57
public Context.Builder allowHostAccess(HostAccess hostAccess);
58
public Context.Builder allowPolyglotAccess(PolyglotAccess polyglotAccess);
59
public Context.Builder allowCreateThread(boolean enabled);
60
public Context.Builder allowNativeAccess(boolean enabled);
61
public Context.Builder allowCreateProcess(boolean enabled);
62
public Context.Builder allowEnvironmentAccess(EnvironmentAccess environmentAccess);
63
public Context.Builder allowIO(IOAccess ioAccess);
64
public Context.Builder allowAllAccess(boolean enabled);
65
66
// Security configuration
67
public Context.Builder sandbox(SandboxPolicy sandbox);
68
69
// Resource management
70
public Context.Builder resourceLimits(ResourceLimits limits);
71
72
// Options and properties
73
public Context.Builder option(String key, String value);
74
public Context.Builder options(Map<String, String> options);
75
public Context.Builder arguments(String language, String[] args);
76
77
// Build the context
78
public Context build();
79
}
80
```
81
82
**Advanced Configuration Example:**
83
84
```java
85
ResourceLimits limits = ResourceLimits.newBuilder()
86
.statementLimit(10000, null)
87
.build();
88
89
Context context = Context.newBuilder("js", "python")
90
.allowHostAccess(HostAccess.EXPLICIT)
91
.allowPolyglotAccess(PolyglotAccess.NONE)
92
.allowIO(IOAccess.NONE)
93
.sandbox(SandboxPolicy.CONSTRAINED)
94
.resourceLimits(limits)
95
.out(System.out)
96
.err(System.err)
97
.build();
98
```
99
100
### Context Operations
101
102
```java { .api }
103
public final class Context implements AutoCloseable {
104
// Context lifecycle
105
public void enter();
106
public void leave();
107
public void close();
108
public void close(boolean cancelIfExecuting);
109
public void interrupt(Duration timeout);
110
public void safepoint();
111
112
// Language management
113
public boolean initialize(String languageId);
114
public Engine getEngine();
115
116
// Bindings and evaluation (detailed in language-execution.md)
117
public Value getBindings(String languageId);
118
public Value getPolyglotBindings();
119
public Value eval(Source source);
120
public Value eval(String languageId, CharSequence source);
121
122
// Value conversion
123
public Value asValue(Object hostValue);
124
125
// Resource management
126
public void resetLimits();
127
}
128
```
129
130
**Context Lifecycle Example:**
131
132
```java
133
Context context = Context.create("js");
134
try {
135
context.enter(); // Make context active for current thread
136
137
// Perform operations...
138
Value result = context.eval("js", "Math.PI * 2");
139
140
} finally {
141
context.leave(); // Always leave context
142
context.close(); // Release resources
143
}
144
```
145
146
## Engine Management
147
148
The Engine provides a shared runtime environment that can be used across multiple contexts for efficiency and resource sharing.
149
150
### Engine Creation
151
152
```java { .api }
153
// Simple engine creation
154
public static Engine create();
155
public static Engine create(String... permittedLanguages);
156
157
// Builder pattern for configuration
158
public static Engine.Builder newBuilder();
159
public static Engine.Builder newBuilder(String... permittedLanguages);
160
161
// Engine discovery
162
public static Engine findEngine(String... permittedLanguages);
163
```
164
165
### Engine Builder Configuration
166
167
```java { .api }
168
public static final class Engine.Builder {
169
// Options and configuration
170
public Engine.Builder option(String key, String value);
171
public Engine.Builder options(Map<String, String> options);
172
173
// I/O stream configuration
174
public Engine.Builder out(OutputStream out);
175
public Engine.Builder err(OutputStream err);
176
177
// Access policies
178
public Engine.Builder allowExperimentalOptions(boolean enabled);
179
180
// Build the engine
181
public Engine build();
182
}
183
```
184
185
### Engine Operations
186
187
```java { .api }
188
public final class Engine implements AutoCloseable {
189
// Language and instrument discovery
190
public Map<String, Language> getLanguages();
191
public Map<String, Instrument> getInstruments();
192
public OptionDescriptors getOptions();
193
194
// Version information
195
public String getVersion();
196
public String getImplementationName();
197
198
// Resource management
199
public void close();
200
public void close(boolean cancelIfExecuting);
201
}
202
```
203
204
**Shared Engine Example:**
205
206
```java
207
// Create shared engine
208
Engine engine = Engine.newBuilder("js", "python")
209
.option("engine.WarnInterpreterOnly", "false")
210
.build();
211
212
// Create multiple contexts sharing the engine
213
Context context1 = Context.newBuilder("js")
214
.engine(engine)
215
.build();
216
217
Context context2 = Context.newBuilder("python")
218
.engine(engine)
219
.build();
220
221
// Both contexts share compilation and optimization state
222
try (context1; context2; engine) {
223
// Use contexts...
224
}
225
```
226
227
## Language and Instrument Metadata
228
229
### Language Information
230
231
```java { .api }
232
public final class Language {
233
public String getId();
234
public String getName();
235
public String getImplementationName();
236
public String getVersion();
237
public Set<String> getMimeTypes();
238
public String getDefaultMimeType();
239
public boolean isInteractive();
240
public OptionDescriptors getOptions();
241
}
242
```
243
244
**Language Discovery Example:**
245
246
```java
247
Engine engine = Engine.create();
248
Map<String, Language> languages = engine.getLanguages();
249
250
for (Language lang : languages.values()) {
251
System.out.printf("Language: %s (%s) v%s%n",
252
lang.getName(), lang.getId(), lang.getVersion());
253
System.out.printf("MIME types: %s%n", lang.getMimeTypes());
254
System.out.printf("Interactive: %s%n", lang.isInteractive());
255
}
256
```
257
258
### Instrument Information
259
260
```java { .api }
261
public final class Instrument {
262
public String getId();
263
public String getName();
264
public String getVersion();
265
public OptionDescriptors getOptions();
266
public <T> T lookup(Class<T> type);
267
}
268
```
269
270
## Resource Management Best Practices
271
272
### Try-with-Resources Pattern
273
274
```java
275
// Automatic resource cleanup
276
try (Engine engine = Engine.create();
277
Context context = Context.newBuilder("js").engine(engine).build()) {
278
279
Value result = context.eval("js", "console.log('Hello World'); 42");
280
281
} // Automatically closes context and engine
282
```
283
284
### Manual Resource Management
285
286
```java
287
Engine engine = null;
288
Context context = null;
289
try {
290
engine = Engine.create("js");
291
context = Context.newBuilder("js").engine(engine).build();
292
293
// Use context...
294
295
} finally {
296
if (context != null) context.close();
297
if (engine != null) engine.close();
298
}
299
```
300
301
### Forced Cleanup
302
303
```java
304
// Force cleanup even if execution is running
305
context.close(true); // Cancel any running execution
306
engine.close(true); // Force engine shutdown
307
```
308
309
## Thread Safety and Context Switching
310
311
### Thread-Local Context Management
312
313
```java
314
Context context1 = Context.create("js");
315
Context context2 = Context.create("python");
316
317
// Thread 1
318
new Thread(() -> {
319
context1.enter();
320
try {
321
context1.eval("js", "console.log('Thread 1')");
322
} finally {
323
context1.leave();
324
}
325
}).start();
326
327
// Thread 2
328
new Thread(() -> {
329
context2.enter();
330
try {
331
context2.eval("python", "print('Thread 2')");
332
} finally {
333
context2.leave();
334
}
335
}).start();
336
```
337
338
### Context Interruption
339
340
```java
341
Context context = Context.create("js");
342
343
// In another thread, interrupt long-running execution
344
new Thread(() -> {
345
try {
346
Thread.sleep(5000); // Wait 5 seconds
347
context.interrupt(Duration.ofSeconds(10)); // Interrupt with timeout
348
} catch (InterruptedException e) {
349
Thread.currentThread().interrupt();
350
}
351
}).start();
352
353
// Main thread - this might be interrupted
354
try {
355
context.eval("js", "while(true) { /* infinite loop */ }");
356
} catch (PolyglotException e) {
357
if (e.isInterrupted()) {
358
System.out.println("Execution was interrupted");
359
}
360
}
361
```
362
363
## Common Types
364
365
```java { .api }
366
// Option descriptors for engine/language configuration
367
public final class OptionDescriptors implements Iterable<OptionDescriptor> {
368
public OptionDescriptor get(String name);
369
public Iterator<OptionDescriptor> iterator();
370
}
371
372
public final class OptionDescriptor {
373
public String getName();
374
public String getHelp();
375
public OptionCategory getCategory();
376
public boolean isDeprecated();
377
public Object getDefaultValue();
378
}
379
380
// Option categories
381
public enum OptionCategory {
382
USER, // User-configurable options
383
EXPERT, // Expert-level options
384
DEBUG // Debug options
385
}
386
```