Java Scripting Engine,在将引用动态传递给回调时获取ReferenceError

时间:2016-11-30 18:35:13

标签: java nashorn jsr223

我正在使用JDK8 Nashorn脚本引擎。我的脚本在Java类中注册回调,如下所示:

stream.create().input(".env/router-memory-list/router1").management().onChange(function(){
    print("onChange: "+input.current());
});

回调函数中引用的input是在执行回调之前从Java线程设置的,并且在(ctx.engineScope是脚本的Binding对象之后)被删除:

            ctx.engineScope.put("input", input);
            input.current(message).executeCallback();
            ctx.engineScope.remove("input");

它通常可以正常工作,但我在执行回调时偶尔会遇到这种错误:

<eval>:15 ReferenceError: "input" is not defined
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
    at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
    at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1432)
    at jdk.nashorn.internal.scripts.Script$Recompilation$4$383$\^eval\_.L:13(<eval>:15)
    at jdk.nashorn.javaadapters.java.lang.Runnable.run(Unknown Source)
    at com.swiftmq.impl.streams.comp.io.ManagementInput.executeCallback(ManagementInput.java:105)
    at com.swiftmq.impl.streams.processor.StreamProcessor.visit(StreamProcessor.java:92)
    at com.swiftmq.impl.streams.processor.po.POMgmtMessage.accept(POMgmtMessage.java:28)
    at com.swiftmq.tools.pipeline.PipelineQueue.process(PipelineQueue.java:35)
    at com.swiftmq.tools.queue.SingleProcessorQueue.dequeue(SingleProcessorQueue.java:135)
    at com.swiftmq.tools.pipeline.PipelineQueue$QueueProcessor.run(PipelineQueue.java:69)
    at com.swiftmq.impl.threadpool.standard.PoolThread.run(Unknown Source) 

我试图用synchronized包围调用代码,希望它可能是一个线程问题,但没有成功。查看堆栈跟踪可能是重新编译问题,其中Binding处动态设置的对象正在丢失。有什么想法吗?

编辑 - 以下是我为此脚本创建Binding的方法:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName((String) entity.getProperty("script-language").getValue());
    if (engine == null)
        throw new Exception("Engine for script-language '" + entity.getProperty("script-language").getValue() + "' not found!");
    ScriptContext newContext = new SimpleScriptContext();
    ctx.engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

0 个答案:

没有答案