The Java Scripting API: Script Engines, Bindings and Invocable
Embedding scripting languages with javax.script (JSR 223): finding engines now that Nashorn is gone, eval, bindings and scopes, redirecting output, Invocable and Java interfaces, Compilable, writing your own engine, and Java snippets via the JShell API.
kvi5hnuCode Sprout team member9 min readOn this page
Scripting languages skip the edit-compile-run cycle: the program text is interpreted when it runs. That makes them attractive inside applications, for user customization, rules that change without redeployment, automation in tools such as JMeter, or quick experiments. The javax.script package (from JSR 223, part of Java since version 6) defines a common API for calling any scripting language from Java: you obtain an engine, hand it code, exchange variables, and call functions. This article explains that API, what changed when the JDK stopped shipping a JavaScript engine, how an engine is built, and how JShell lets Java itself play the scripting role.
Finding an engine
A script engine is a library that executes one language. Engines are discovered through ScriptEngineManager, which uses the ServiceLoader mechanism to find every ScriptEngineFactory on the class path or module path:
var manager = new ScriptEngineManager();
for (ScriptEngineFactory f : manager.getEngineFactories())
System.out.println(f.getEngineName() + " " + f.getNames() + " " + f.getExtensions());
ScriptEngine engine = manager.getEngineByName("groovy"); // or getEngineByExtension / getEngineByMimeType
The lookup methods return null when no engine matches, so check the result.
Engines differ in which optional interfaces they implement and in how well they support threads. factory.getParameter("THREADING") tells you: null (not thread-safe), "MULTITHREADED" (safe, but state is shared), "THREAD-ISOLATED" (each thread has its own bindings) or "STATELESS" (scripts don't change bindings). For a null engine, create one engine per thread or synchronize.
Evaluating scripts
eval runs code from a String or a Reader and returns the value of the last expression (exactly what is returned depends on the language):
engine.eval("n = 1728");
Object result = engine.eval("n + 1"); // 1729
Most engines keep definitions between calls, so a script can define variables and functions that later scripts use. Problems in the script are reported as ScriptException, which may carry a file name, line and column (getFileName, getLineNumber, getColumnNumber).
Bindings and scopes
The main way to exchange data between Java and scripts is through bindings, maps from names to Java objects:
engine.put("taxRate", 0.2); // engine scope
manager.put("discount", 5); // global scope, shared by all engines of this manager
engine.eval("100 * (1 + taxRate) - discount");
Object n = engine.get("n"); // read a variable the script defined

A ScriptContext holds the scopes and searches them in order of their numbers: ENGINE_SCOPE (100) before GLOBAL_SCOPE (200). Scripts in languages with Java interop can also call methods on the objects you bind, for example d.month on a LocalDate in JavaScript.
When a set of values should not persist, create fresh bindings and pass them to eval:
Bindings scope = engine.createBindings();
scope.put("taxRate", 0.07);
engine.eval(script, scope); // uses scope in place of the engine scope
This is how a server would run the same script for many requests, each with its own data. For additional scopes (request, session), implement ScriptContext yourself; SimpleScriptContext only has the two standard ones.
Redirecting input and output
Script output functions such as print write to the context's writer, which you can replace:
var out = new StringWriter();
engine.getContext().setWriter(new PrintWriter(out, true));
setReader and setErrorWriter do the same for input and error output. This only affects the language's own I/O functions: if a script calls java.lang.System.out.println directly, the output goes to System.out as usual.
Calling script functions from Java: Invocable
Engines that implement Invocable let Java call functions defined by scripts directly, without building source strings:
engine.eval("def square(x) = x * x"); // Calc syntax from the demo
Object r = ((Invocable) engine).invokeFunction("square", 12);
For object-oriented languages, invokeMethod(scriptObject, "name", args...) calls a method on an object the script created.
Even better, getInterface(Class<T>) returns an implementation of a Java interface whose methods are backed by script functions of the same names:
public interface Pricing { double price(double base, double qty); }
Pricing p = ((Invocable) engine).getInterface(Pricing.class);
p.price(10, 3);
The rest of the application can use Pricing without knowing that a script stands behind it, and when the script redefines price, the next call uses the new definition. getInterface(scriptObject, type) does the same for a script object's methods. getInterface returns null if the script does not define all the methods.
Compiling scripts: Compilable
Engines that implement Compilable can parse a script once into a CompiledScript and run it many times, with different bindings each time:
if (engine instanceof Compilable c) {
CompiledScript script = c.compile("x * x + 2 * x + 1");
Bindings b = engine.createBindings();
for (int x = 0; x <= 4; x++) { b.put("x", x); script.eval(b); }
}
This pays off for scripts that run repeatedly, such as rules evaluated for every order.
Inside an engine
Because the JDK no longer includes an engine, the demo implements a small one for a calculator language named Calc. It shows the pieces every engine has:
- A
ScriptEngineFactorydescribes the engine: names (calc), extensions, MIME types, version information and parameters such asTHREADING, plus helpers likegetOutputStatementandgetProgramthat generate code in the language. - The engine extends
AbstractScriptEngine, which provides the default context and theput/get/eval(String)convenience methods. You implementeval(Reader, ScriptContext),eval(String, ScriptContext),createBindingsandgetFactory. - Variables are read with
context.getAttribute(name), which searches the scopes in order, and assigned withsetAttribute(name, value, ENGINE_SCOPE). InvocableandCompilableare optional. The demo'sgetInterfaceuses a dynamic proxy, the same technique real engines use.
A real engine is registered for discovery by listing the factory class in META-INF/services/javax.script.ScriptEngineFactory in its JAR, or with provides javax.script.ScriptEngineFactory with ... in its module-info.java. For an engine you create in your own program, manager.registerEngineName and registerEngineExtension register it directly, as the demo does.
Java as a scripting language: JShell
Sometimes the "script" should simply be Java. The jdk.jshell module, the engine behind the jshell tool, offers an API to evaluate Java snippets one at a time:
try (JShell shell = JShell.builder().executionEngine("local").build()) {
for (SnippetEvent e : shell.eval("int n = 1728;")) System.out.println(e.value());
shell.eval("n + 1"); // value "1729"
}
Each eval returns SnippetEvents with the snippet's kind (variable, method, class, expression), status (VALID, REJECTED, ...) and its value as a string. Expressions become temporary variables ($1, $2, ...). Errors are available as diagnostics through shell.diagnostics(snippet). By default JShell runs the code in a separate JVM, which isolates crashes; executionEngine("local") runs it in the same JVM, which is faster but shares the process. Article 78's in-memory compilation is the other option when you need classes rather than snippets.
The program
The demo checks which engines the JDK provides (none), registers the Calc engine, and uses it to show evaluation, scopes, separate bindings, output redirection, Invocable with a Java interface, Compilable, and error reporting. It ends by evaluating Java snippets with the JShell API.
import java.io.*;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.function.*;
import javax.script.*;
import jdk.jshell.*;
public class Solution {
// ---------------------------------------------------------------- a tiny JSR 223 language
// Statements (one per line): name = expr | def f(a, b) = expr | print expr | expr
// Expressions: numbers, names, + - * / %, unary -, parentheses, calls f(x, y)
static final class CalcFactory implements ScriptEngineFactory {
public String getEngineName() { return "Calc"; }
public String getEngineVersion() { return "1.0"; }
public List<String> getExtensions() { return List.of("calc"); }
public List<String> getMimeTypes() { return List.of("text/x-calc"); }
public List<String> getNames() { return List.of("calc", "Calc"); }
public String getLanguageName() { return "Calc"; }
public String getLanguageVersion() { return "1"; }
public Object getParameter(String key) {
return switch (key) {
case ScriptEngine.NAME -> "calc";
case ScriptEngine.ENGINE -> getEngineName();
case ScriptEngine.ENGINE_VERSION -> getEngineVersion();
case ScriptEngine.LANGUAGE -> getLanguageName();
case ScriptEngine.LANGUAGE_VERSION -> getLanguageVersion();
case "THREADING" -> null; // not safe for concurrent use
default -> null;
};
}
public String getMethodCallSyntax(String obj, String m, String... args) {
throw new UnsupportedOperationException("Calc has no objects");
}
public String getOutputStatement(String toDisplay) { return "print " + toDisplay; }
public String getProgram(String... statements) { return String.join("\n", statements); }
public ScriptEngine getScriptEngine() { return new CalcEngine(this); }
}
interface Node { double eval(Env env); }
record Env(ScriptContext ctx, Map<String, Double> locals, CalcEngine engine) {}
record Func(List<String> params, Node body) {}
static final class CalcEngine extends AbstractScriptEngine implements Invocable, Compilable {
private final CalcFactory factory;
final Map<String, Func> functions = new HashMap<>();
CalcEngine(CalcFactory factory) { this.factory = factory; }
public ScriptEngineFactory getFactory() { return factory; }
public Bindings createBindings() { return new SimpleBindings(); }
public Object eval(Reader reader, ScriptContext ctx) throws ScriptException {
return eval(readAll(reader), ctx);
}
public Object eval(String script, ScriptContext ctx) throws ScriptException {
return compile(script).eval(ctx);
}
public CompiledScript compile(Reader reader) throws ScriptException { return compile(readAll(reader)); }
public CompiledScript compile(String script) throws ScriptException {
List<Stmt> program = new ArrayList<>();
String[] lines = script.split("\\R");
for (int i = 0; i < lines.length; i++) {
String line = lines[i].strip();
if (line.isEmpty() || line.startsWith("#")) continue;
try {
program.add(Parser.statement(line));
} catch (IllegalArgumentException e) {
throw new ScriptException(e.getMessage(), "<calc>", i + 1);
}
}
return new CompiledScript() {
public Object eval(ScriptContext ctx) throws ScriptException {
Object last = null;
for (Stmt s : program) last = s.run(CalcEngine.this, ctx);
try { ctx.getWriter().flush(); } catch (IOException e) { throw new ScriptException(e); }
return last;
}
public ScriptEngine getEngine() { return CalcEngine.this; }
};
}
public Object invokeFunction(String name, Object... args) throws NoSuchMethodException {
Func f = functions.get(name);
if (f == null) throw new NoSuchMethodException(name);
return call(f, args, context);
}
public Object invokeMethod(Object thiz, String name, Object... args) throws NoSuchMethodException {
throw new NoSuchMethodException("Calc has no objects");
}
public <T> T getInterface(Class<T> type) {
for (var m : type.getMethods())
if (!functions.containsKey(m.getName())) return null; // spec: null if not implementable
return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type},
(proxy, method, args) -> {
Object r = invokeFunction(method.getName(), args == null ? new Object[0] : args);
return method.getReturnType() == int.class ? (Object) (int) (double) (Double) r : r;
}));
}
public <T> T getInterface(Object thiz, Class<T> type) { return null; }
Double call(Func f, Object[] args, ScriptContext ctx) {
Map<String, Double> locals = new HashMap<>();
for (int i = 0; i < f.params().size(); i++)
locals.put(f.params().get(i), ((Number) args[i]).doubleValue());
return f.body().eval(new Env(ctx, locals, this));
}
private static String readAll(Reader r) throws ScriptException {
try { return new BufferedReader(r).lines().reduce("", (a, b) -> a + b + "\n"); }
catch (UncheckedIOException e) { throw new ScriptException(e); }
}
}
interface Stmt { Object run(CalcEngine engine, ScriptContext ctx) throws ScriptException; }
static final class Parser {
private final String s;
private int pos;
private Parser(String s) { this.s = s; }
static Stmt statement(String line) {
if (line.startsWith("def ")) {
int eq = line.indexOf('=');
String head = line.substring(4, eq).strip();
String name = head.substring(0, head.indexOf('(')).strip();
List<String> params = Arrays.stream(head.substring(head.indexOf('(') + 1, head.indexOf(')')).split(","))
.map(String::strip).filter(p -> !p.isEmpty()).toList();
Node body = expression(line.substring(eq + 1));
return (engine, ctx) -> { engine.functions.put(name, new Func(params, body)); return null; };
}
if (line.startsWith("print ")) {
Node e = expression(line.substring(6));
return (engine, ctx) -> {
double v = e.eval(new Env(ctx, Map.of(), engine));
try { ctx.getWriter().write(format(v) + "\n"); } catch (IOException ex) { throw new ScriptException(ex); }
return null;
};
}
int eq = line.indexOf('=');
if (eq > 0 && line.substring(0, eq).strip().matches("[A-Za-z_]\\w*")) {
String name = line.substring(0, eq).strip();
Node e = expression(line.substring(eq + 1));
return (engine, ctx) -> {
double v = e.eval(new Env(ctx, Map.of(), engine));
ctx.setAttribute(name, v, ScriptContext.ENGINE_SCOPE);
return v;
};
}
Node e = expression(line);
return (engine, ctx) -> e.eval(new Env(ctx, Map.of(), engine));
}
static Node expression(String text) {
Parser p = new Parser(text);
Node n = p.sum();
p.skip();
if (p.pos != p.s.length()) throw new IllegalArgumentException("Unexpected '" + p.s.charAt(p.pos) + "' at column " + (p.pos + 1));
return n;
}
private void skip() { while (pos < s.length() && s.charAt(pos) == ' ') pos++; }
private boolean eat(char c) { skip(); if (pos < s.length() && s.charAt(pos) == c) { pos++; return true; } return false; }
private Node sum() {
Node left = product();
while (true) {
if (eat('+')) { Node l = left, r = product(); left = env -> l.eval(env) + r.eval(env); }
else if (eat('-')) { Node l = left, r = product(); left = env -> l.eval(env) - r.eval(env); }
else return left;
}
}
private Node product() {
Node left = unary();
while (true) {
if (eat('*')) { Node l = left, r = unary(); left = env -> l.eval(env) * r.eval(env); }
else if (eat('/')) { Node l = left, r = unary(); left = env -> l.eval(env) / r.eval(env); }
else if (eat('%')) { Node l = left, r = unary(); left = env -> l.eval(env) % r.eval(env); }
else return left;
}
}
private Node unary() {
if (eat('-')) { Node n = unary(); return env -> -n.eval(env); }
return primary();
}
private Node primary() {
skip();
if (eat('(')) { Node n = sum(); if (!eat(')')) throw new IllegalArgumentException("Missing ')'"); return n; }
int start = pos;
if (pos < s.length() && (Character.isDigit(s.charAt(pos)) || s.charAt(pos) == '.')) {
while (pos < s.length() && (Character.isDigit(s.charAt(pos)) || s.charAt(pos) == '.')) pos++;
double v = Double.parseDouble(s.substring(start, pos));
return env -> v;
}
while (pos < s.length() && (Character.isLetterOrDigit(s.charAt(pos)) || s.charAt(pos) == '_')) pos++;
if (start == pos) throw new IllegalArgumentException(pos < s.length()
? "Unexpected '" + s.charAt(pos) + "' at column " + (pos + 1) : "Unexpected end of input");
String name = s.substring(start, pos);
if (eat('(')) {
List<Node> args = new ArrayList<>();
if (!eat(')')) {
do args.add(sum()); while (eat(','));
if (!eat(')')) throw new IllegalArgumentException("Missing ')' after arguments");
}
return env -> {
Func f = env.engine().functions.get(name);
if (f == null) throw new IllegalStateException("Unknown function " + name);
Object[] vals = args.stream().map(a -> (Object) a.eval(env)).toArray();
return env.engine().call(f, vals, env.ctx());
};
}
return env -> {
if (env.locals().containsKey(name)) return env.locals().get(name);
Object v = env.ctx().getAttribute(name); // searches ENGINE_SCOPE, then GLOBAL_SCOPE
if (v == null) throw new IllegalStateException("Unknown variable " + name);
return ((Number) v).doubleValue();
};
}
}
static String format(double v) {
return v == Math.rint(v) && Math.abs(v) < 1e15 ? String.valueOf((long) v) : String.valueOf(v);
}
public interface Pricing { double price(double base, double qty); }
// ---------------------------------------------------------------- the demo
public static void main(String[] args) throws Exception {
var manager = new ScriptEngineManager();
System.out.println("== Engines discovered on this JDK ==");
System.out.println("factories: " + manager.getEngineFactories().size()
+ ", javascript engine: " + manager.getEngineByName("javascript"));
manager.registerEngineName("calc", new CalcFactory());
manager.registerEngineExtension("calc", new CalcFactory());
ScriptEngine engine = manager.getEngineByName("calc");
System.out.println("registered: " + engine.getFactory().getEngineName()
+ " (by extension: " + (manager.getEngineByExtension("calc") != null) + ")");
System.out.println("THREADING parameter: " + engine.getFactory().getParameter("THREADING"));
System.out.println("\n== eval and state between calls ==");
engine.eval("n = 1728");
System.out.println("n + 1 -> " + format((Double) engine.eval("n + 1")));
System.out.println("engine.get(\"n\") -> " + engine.get("n"));
System.out.println("\n== Bindings and scopes ==");
engine.put("taxRate", 0.2);
manager.put("discount", 5);
System.out.println("100 * (1 + taxRate) - discount -> "
+ format((Double) engine.eval("100 * (1 + taxRate) - discount")));
Bindings temp = engine.createBindings();
temp.put("taxRate", 0.07);
temp.put("discount", 0);
System.out.println("with separate bindings -> " + format((Double) engine.eval("100 * (1 + taxRate) - discount", temp)));
System.out.println("engine scope unchanged -> " + engine.get("taxRate"));
ScriptContext ctx = engine.getContext();
System.out.println("scopes: ENGINE=" + ScriptContext.ENGINE_SCOPE + " GLOBAL=" + ScriptContext.GLOBAL_SCOPE
+ ", 'discount' found in scope " + ctx.getAttributesScope("discount"));
System.out.println("\n== Redirecting output ==");
var out = new StringWriter();
ctx.setWriter(new PrintWriter(out, true));
engine.eval("""
# a script with output
print 6 * 7
print n / 12
""");
System.out.println("captured: " + out.toString().strip().replace("\n", " | "));
ctx.setWriter(new PrintWriter(System.out, true));
System.out.println("\n== Invocable: functions and interfaces ==");
engine.eval("""
def square(x) = x * x
def price(base, qty) = base * qty * (1 + taxRate) - discount
""");
Invocable inv = (Invocable) engine;
System.out.println("square(12) -> " + format((Double) inv.invokeFunction("square", 12)));
Pricing pricing = inv.getInterface(Pricing.class);
System.out.println("Pricing.price(10, 3) -> " + format(pricing.price(10, 3)));
engine.eval("def price(base, qty) = base * qty");
System.out.println("after redefining in the script -> " + format(pricing.price(10, 3)));
try {
inv.invokeFunction("missing");
} catch (NoSuchMethodException e) {
System.out.println("NoSuchMethodException: " + e.getMessage());
}
System.out.println("getInterface(Runnable) -> " + inv.getInterface(Runnable.class));
System.out.println("\n== Compilable ==");
CompiledScript compiled = ((Compilable) engine).compile("x * x + 2 * x + 1");
Bindings b = engine.createBindings();
StringJoiner sj = new StringJoiner(" ");
for (int x = 0; x <= 4; x++) {
b.put("x", x);
sj.add(format((Double) compiled.eval(b)));
}
System.out.println("(x+1)^2 for x = 0..4: " + sj);
System.out.println("\n== Errors ==");
for (String bad : List.of("2 * (3 + 4", "print 1 +", "unknownVar * 2")) {
try {
engine.eval(bad);
} catch (ScriptException e) {
System.out.println("ScriptException line " + e.getLineNumber() + ": " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("runtime error: " + e.getMessage());
}
}
System.out.println("\n== Java itself as the scripting language: the JShell API ==");
try (JShell shell = JShell.builder().executionEngine("local").build()) {
for (String snippet : List.of("int n = 1728;", "n + 1", "String greet(String s) { return \"Hi \" + s; }",
"greet(\"jshell\")", "var list = java.util.List.of(3, 1, 2);", "list.stream().sorted().toList()",
"n.length()")) {
for (SnippetEvent ev : shell.eval(snippet)) {
if (ev.status() == Snippet.Status.REJECTED) {
String msg = shell.diagnostics(ev.snippet()).findFirst()
.map(d -> d.getMessage(Locale.US).lines().findFirst().orElse("")).orElse("");
System.out.println("rejected: " + snippet + " -> " + msg);
} else {
System.out.println(ev.snippet().kind() + " " + snippet + " -> " + ev.value());
}
}
}
}
}
}
== Engines discovered on this JDK ==
factories: 0, javascript engine: null
registered: Calc (by extension: true)
THREADING parameter: null
== eval and state between calls ==
n + 1 -> 1729
engine.get("n") -> 1728.0
== Bindings and scopes ==
100 * (1 + taxRate) - discount -> 115
with separate bindings -> 107
engine scope unchanged -> 0.2
scopes: ENGINE=100 GLOBAL=200, 'discount' found in scope 200
== Redirecting output ==
captured: 42 | 144
== Invocable: functions and interfaces ==
square(12) -> 144
Pricing.price(10, 3) -> 31
after redefining in the script -> 30
NoSuchMethodException: missing
getInterface(Runnable) -> null
== Compilable ==
(x+1)^2 for x = 0..4: 1 4 9 16 25
== Errors ==
ScriptException line 1: Missing ')' in <calc> at line number 1
ScriptException line 1: Unexpected end of input in <calc> at line number 1
runtime error: Unknown variable unknownVar
== Java itself as the scripting language: the JShell API ==
VAR int n = 1728; -> 1728
VAR n + 1 -> 1729
METHOD String greet(String s) { return "Hi " + s; } -> null
VAR greet("jshell") -> "Hi jshell"
VAR var list = java.util.List.of(3, 1, 2); -> [3, 1, 2]
VAR list.stream().sorted().toList() -> [1, 2, 3]
rejected: n.length() -> int cannot be dereferenced
Common questions
Why does getEngineByName("js") return null?
The JDK hasn't included a JavaScript engine since Java 15. Add one as a dependency, such as org.openjdk.nashorn:nashorn-core (needs Java 11 or later) or GraalJS with its JSR 223 support, and the same call works again.
Which scripting language should I embed? For users who know Java, Groovy is the most familiar. JavaScript (GraalJS) suits web developers. For simple, safe rules, an expression language like SpEL, MVEL or JEXL, or a small custom language, gives more control than a full language.
Can a script access my whole application?
With engines that support Java interop, often yes: scripts can call any public class, including System.exit or file APIs. Most engines offer restrictions (GraalJS's HostAccess, Nashorn's ClassFilter), and you should use them for scripts from users.
Is ScriptEngine thread-safe?
Check factory.getParameter("THREADING"). If it's null, use one engine per thread, or pool engines. Compiled scripts with separate bindings per call are the usual pattern for servers.
When should I use JShell's API instead of a script engine? When the "scripts" should be Java snippets, for example in teaching tools, notebooks or interactive consoles. It's heavier than a script engine (it compiles each snippet) and, by default, runs code in a separate JVM.
API reference
| Method | Purpose |
|---|---|
new ScriptEngineManager(), getEngineFactories() | discover engines |
getEngineByName, getEngineByExtension, getEngineByMimeType | select an engine (or null) |
registerEngineName, registerEngineExtension, registerEngineMimeType | register a factory manually |
ScriptEngineFactory.getNames/getExtensions/getMimeTypes/getParameter | engine metadata |
ScriptEngine.eval(String or Reader[, Bindings or ScriptContext]) | run a script |
ScriptEngine.put/get, ScriptEngineManager.put/get, createBindings() | variables and scopes |
ScriptContext.getAttribute, setAttribute, getAttributesScope, setWriter, setReader, setErrorWriter | context and I/O |
Invocable.invokeFunction, invokeMethod, getInterface | call into scripts |
Compilable.compile, CompiledScript.eval([bindings]) | precompiled scripts |
AbstractScriptEngine | base class for engines |
JShell.create()/builder(), eval, diagnostics, SnippetEvent.value() | evaluate Java snippets |
Summary
javax.scriptis a language-neutral API for embedding scripting languages; engines are found byScriptEngineManagerthrough service loading.- Since Java 15 the JDK contains no engine; add Nashorn, GraalJS, Rhino, Groovy or another JSR 223 implementation.
- Exchange data with bindings: engine scope before global scope; pass separate
Bindingsfor per-call data. - Redirect script I/O through the
ScriptContext. Invocablecalls script functions and turns them into Java interface implementations;Compilableparses scripts once for repeated use.- Check
THREADINGbefore sharing an engine between threads. - For Java snippets, use the JShell API; for whole classes, the Compiler API.
Practice Questions
1. Code that ran on Java 11 now fails with a NullPointerException after new ScriptEngineManager().getEngineByName("nashorn").eval(...). Why?
Nashorn was removed from the JDK in Java 15, so the lookup returns null. Add a JavaScript engine to the dependencies, for example standalone Nashorn (org.openjdk.nashorn:nashorn-core) or GraalJS, and check the result of getEngineByName for null with a clear error message.
2. A web application evaluates the same pricing script for each request with engine.put("order", order). Under load, prices are sometimes computed with another request's order. What is wrong and how do you fix it?
engine.put writes to the engine scope, which all threads share, so concurrent requests overwrite each other's order. Create fresh Bindings per request and call engine.eval(script, bindings) (or compiledScript.eval(bindings)), and check the factory's THREADING parameter; if it is null, use one engine per thread or a pool of engines.
3. What is the advantage of getInterface over invokeFunction?
getInterface gives you an ordinary Java object implementing your interface, so the rest of the program calls typed methods and does not know that a script implements them. You get compile-time checking of method names and argument types on the Java side, and you can swap a script implementation for a Java one without changing callers. invokeFunction requires string names and Object arguments and results.
4. A script calls both print("A") and java.lang.System.out.println("B") after engine.getContext().setWriter(myWriter). Where do A and B go?
A goes to myWriter, because the language's print function writes to the context's writer. B goes to the real System.out, because the script calls the Java method directly and the scripting API does not redirect System.out.
5. When would you use the JShell API instead of a JSR 223 engine?
When users or configuration should be written in Java itself: evaluating Java expressions or snippets, building an interactive console or notebook, or teaching tools. JShell needs no extra language runtime, understands the full Java language and reports compiler diagnostics. JSR 223 engines are the choice when the script language is something else (JavaScript, Groovy, Python) or when you need the uniform engine API.
Previous: Compiling Java Code in Memory: Custom File Objects and Dynamic Code Generation
Next: Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces
Related reading
- Compiling Java Code in Memory: Custom File Objects and Dynamic Code Generation
- Invoking the Java Compiler from Code: JavaCompiler, Tasks and Diagnostics
- Resource Bundles in Java: Locating Bundles, Property Files and Bundle Classes
- Text Boundaries, Line Endings, Console and Encodings in Java
- MessageFormat and ChoiceFormat in Java: Placeholders, Plurals and Choices

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.