Heuristic:APIJSON APIJSON Demo ConcurrentHashMap For GraalVM Source Caching
| Knowledge Sources | |
|---|---|
| Domains | Caching, Concurrency, Scripting |
| Last Updated | 2026-10-14 00:00 GMT |
Overview
Use ConcurrentHashMap<String, Source> for thread-safe caching of compiled GraalVM script sources, enabling lock-free lookups while the GraalVM Engine is shared across threads.
Description
The GraalJavaScriptExecutor caches compiled GraalVM Source objects in a ConcurrentHashMap. The load() method compiles JavaScript text into a Source via Source.create("js", script) and stores it. The execute() method performs a lock-free scriptMap.get(methodName) lookup, then creates a fresh Context per call. This design separates the thread-safe cache (shared Source objects are immutable) from the per-call execution context (which is mutable and isolated). The GraalVM Engine is created once in init() and shared, reducing context creation overhead.
Usage
Apply this heuristic when caching compiled script objects for a polyglot engine. Use ConcurrentHashMap for the cache, share the Engine, and create fresh Context instances per execution.
The Insight (Rule of Thumb)
- Action: Store compiled
Sourceobjects inConcurrentHashMap; shareEngine; create per-callContext. - Value: Cache key = script function name; cached value = immutable
Source. - Trade-off: Slightly higher memory for multiple
Contextinstances, offset by thread safety without locking. - Compatibility: GraalVM
Sourceobjects are immutable and safe to share;Contextobjects are not.
Reasoning
GraalVM Source objects are immutable once created — they represent compiled script code and can be safely shared across threads. Context objects, however, hold execution state (bindings, heap) and must not be shared. By caching Source in a ConcurrentHashMap, lookups are lock-free and scalable. Creating a fresh Context per call prevents cross-request contamination (a security concern for server-side scripting). The shared Engine enables cross-context optimization and reduces startup cost.
Code Evidence
ConcurrentHashMap cache from `GraalJavaScriptExecutor.java:19`:
private final Map<String, Source> scriptMap = new ConcurrentHashMap<>();
Source compilation and caching from `GraalJavaScriptExecutor.java:34-39`:
@Override
public void load(String name, String script) {
try {
scriptMap.put(name, Source.create("js", script));
} catch (Exception e) {
e.printStackTrace();
}
}
Per-call context with shared engine from `GraalJavaScriptExecutor.java:44`:
Context context = Context.newBuilder().allowAllAccess(true).engine(this.engine).build();