Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate from Nashorn: create new context for multithread support #952

Closed
ValentinaBaranova opened this issue Feb 1, 2019 · 2 comments
Closed

Comments

@ValentinaBaranova
Copy link

We're trying to migrate our Java + Javascript project from Nashorn to Graal. In our project we had js files which are loaded when application starts. When java application receives some event, it calls js function with this event as parameter.
As I understand according oracle/graaljs#59, for multithreading support we need create org.graalvm.polyglot.Context each time when we call our js function and call "eval" for js file and it's dependencies.
Because of this we should not use classes from JDK like javax.script.ScriptEngine because we cannot transfer polyglot context to them. So we should use poliglot api and our code shold be like this:

//once after application start 
Source source = Source.newBuilder("js",  file.toFile()).build();

//every time when we need call js function from java
try (Context context = Context.newBuilder().option("js.nashorn-compat", "true").engine(Engine.create()).build()) {
    context.eval(source);
    context.getBindings("js").getMember("a").execute(params);
}

Is it correct?

@chumer
Copy link
Member

chumer commented Feb 1, 2019

A few remarks:

  1. You need to create a JS context for each parallel thread, not necessarily for each script (depends on your use-case whether you want to allow the global object between scripts to be shared).
  2. You may want to allow some AST sharing between your contexts. See this: http://www.graalvm.org/docs/graalvm-as-a-platform/embed/#enable-source-caching
  3. You may use the script engine API and instead enable Nashorn compatibility using -Dpolyglot.js.nashorn-compat=true as JVM argument. That being said we recommend using the polyglot API as it provides the most features.
  4. Alternatively, you may use GraalJSScriptEngine#create to initialize the script engine from a custom polyglot Context.

Please close if this answers your questions.

@ValentinaBaranova
Copy link
Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants