Reputation: 45
Note, I use both Nashhorn and Graal, so it's possible that the ScriptEngine
used below is an instance of GraalJSScriptEngine or the nashhorn engine.
When I call createBindings
using the GraalJSScriptEngine engine:
Bindings bindings = scriptEngine.createBindings();
it returns a GraalJSBindings object, which has a close
function which closes the context associated with the bindings:
@Override
public void close() {
if (context != null) {
context.close();
}
}
In my application, I had to make sure to close this context after each use, via GraalJSBindings.close()
, this was to prevent a memory leak in which the contexts were not getting GC'ed. For example:
// Create bindings
Bindings bindings = scriptEngine.createBindings();
// Do stuff
...
// Close bindings if they implement AutoClosable
// I also use the Nashhorn engine, so its possible that bindings
// may not be an instance of AutoCloseable/GraalJSBindings
if (bindings instanceof AutoCloseable) {
try {
((AutoCloseable) bindings ).close();
} catch (final RuntimeException re) {
throw re;
} catch (final Exception ex) {
LOGGER.error("Unable to close script bindings and associated context", ex);
}
}
I noticed there is another way to create bindings, not via the engine, but by explicitly instantiating a SimpleBindings
object. I am wondering what the difference is in the following, i.e. could I simple just replace scriptEngine.createBindings()
with new SimpleBindings()
and avoid having to close the bindings like I am doing above? Or is there some advantage to using scriptEngine.createBindings()
?
Bindings bindings = graalJSScriptEngine.createBindings();
vs
Bindings bindings = new SimpleBindings();
Upvotes: 2
Views: 347
Reputation: 296
internally, SimpleBindings
are wrapped in a GraalJSBindings
object. So effectively, the behaviour should be identical.
The performance of GraalJSBindings
might be better though, especially if you repeatedly eval
code for the same bindings. And GraalJSBindings
allows to manipulate the bindings while they are evaluated (from a different thread).
Best, Christian
Upvotes: 1