使用Nashorn的Java脚本(JSR 223)&预编译 [英] Java Scripting With Nashorn (JSR 223) & Pre-compilation

查看:116
本文介绍了使用Nashorn的Java脚本(JSR 223)&预编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过JSR 223使用Nashorn来执行用户输入脚本的小片段:

I am using Nashorn via JSR 223 to execute small snippets of user entered script:

public Invocable buildInvocable(String script) throws ScriptException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName(ENGINE);
    engine.eval(functions);
    engine.eval(script);
    return (Invocable) engine;
}

不同的用户脚本调用静态中央库中定义的JavaScript函数(保存在上面代码片段中的函数字符串中)。

The varying user script calls JavaScript functions that are defined in a static, central library (held in the functions String in the code snippet above).

每次我想抓住一个我可以从Java调用的 Invocable 我不断重新编译大型库代码。

Every time I want to get hold of an Invocable that I can call from my Java I am constantly having to recompile the large library code.

有没有用新代码加入以前编译的代码片段的方法?

Is there any way to join a previously compiled piece of code in with new code?

推荐答案

这是JSR-223的设计; eval(String)后面没有真正的代码缓存。嗯,理论上它可以,但它体现了开发人员想要的很多猜测(并且在所有猜测中,它在某些时候肯定是错误的)。

This is by design of JSR-223; eval(String) can't really have a code cache behind it. Well, theoretically it could, but it'd embody a lot of speculation on the part of what the developer wants (and as all speculations, it'd be bound to be wrong some of the time).

你应该做的是评估你的 Invocable 一次,保留它并反复使用它。

What you should do is evaluate your Invocable once, keep it around and use it repeatedly.

当这样做时,请注意Nashorn不提供线程安全性(JavaScript没有线程概念,所以Nashorn故意不是线程安全的,以便在它们没有时不必支付同步成本不受语言语义的限制。因此,对于底层脚本中全局变量的状态,您创建的 Invocable 在多个线程中使用是不安全的。 (同时运行不与脚本的全局状态交互的函数很好。)

When doing so, note that Nashorn does not provide thread safety (JavaScript has no concept of threading, so Nashorn is intentionally not thread safe in order to not have to pay synchronization costs when they aren't mandated by the language semantics). For that reason, your created Invocable will not be safe to use from multiple threads with regard to the state of the global variables in the underlying script. (Concurrently running functions that don't interact with the script's global state is fine.)

如果需要跨线程共享它函数依赖于全局状态,全局状态可以改变,那么你需要为它添加自己的脚手架(同步,或资源池,或者为此目的时尚的其他任何东西) )。

If you need to share it across threads and the functions depend on global state, and the global state can change, then you'll need to add your own scaffolding for that (either synchronization, or resource pooling, or whatever else is currently in fashion for this purpose).

这篇关于使用Nashorn的Java脚本(JSR 223)&预编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆