ScriptEngines sharing global variables across threads

yikes aroni yikesaroni at gmail.com
Wed May 22 15:40:40 UTC 2019


Hi all ... So I thought i had this figured out, but apparently i did not.

The way i use ScriptEngines is, for each Java thread, i instantiate a
ScriptEngine like this more or less... I have a NashornScriptEngineFactory
in a class that is static and final:

private static final NashornScriptEngineFactory nashornFactory = new
NashornScriptEngineFactory();

And i use that class to generate a script engine for each thread.
ScriptEngine scriptEngine = nashornFactory.getScriptEngine()

However, i just ran a test in which i generate a few threads (each with a
single ScriptEngine instance bound to it), and invoke the JS function

var Thread = Java.type('java.lang.Thread');

var fn = function () {

    myvar = Thread.currentThread().getName();

    if (myvar != Thread.currentThread().getName()) {

        print('From ' + Thread.currentThread().getName() + ': ' + myvar);

    }

};

Note that "myvar" is undeclared, so it goes into the global namespace.
Then, what this script does is a) get the name of the current thread and
write it to "myvar" in the global namespace; b) check the "myvar" in the
global namespace to validate that it is equal to the name of the thread
and, if not, to pring out the name of the current thread and the value of
the "myvar" variable.

Sample of output is

>From qtp140110402-35: qtp140110402-34

>From qtp140110402-37: qtp140110402-32

>From qtp140110402-37: qtp140110402-35

So my question is: is it possible to create a multiple threads, bind a
scriptengine instance to each of them, and guarantee that they do not share
global namespace?

thank you!


More information about the nashorn-dev mailing list