开发者

Java Scripting API, managing state and common functionality

I want to extend our Java application with scripting functionality by using user-editable Groovy scriptlets.

My problem is that the Java Scripting API documentation is a little bit laconic about the API usage patterns.

So my use case is: There are a lots of Groovy scripts (no coding structure or objects, just procedural code line-by-line) that need to run in complete separation and isolation in multi-threaded environment, they are given some objects to work on with Bindings (so it should be possible to run the same script开发者_StackOverflow中文版 on different input parameters in parallel, and I guarantee that the input parameters are not the same object instances). And also I want to create some common functionality that can be used in every script.

My questions are:

  • Do I need a new instance of the ScriptEngine (acquired through ScriptEngineManager) for every executions or a single ScriptEngine instance can be used for ALL executions? This is a great concern of mine, that how the ScriptEngine instances (and their bindings) behave under concurrent use. Currently I use ScriptEngine.eval(Bindings) with different bindings during each execution.
  • How should I add the common functionalities? It would be OK if I could somehow make some common methods available for all scripts.
  • Are there any major gotchas?

I think this section of the Java API is highly undocumented...


Threading behaviour is described in section SCR.4.3.5.1 of JSR 223 spec. The groovy engine reports itself to be multithreaded:

import javax.script.*
def engine = new ScriptEngineManager().getEngineByName("groovy")
assert engine.factory.getParameter("THREADING") == "MULTITHREADED"

This means it's safe to use the script engine in multiple threads, as long as the scripts themselves are thread safe.

For common functionalities, just put them into classes and import them into your scripts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜