热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

试图使Nashorn线程安全-AttemptingtomakeNashornthreadsafe

IverecentlybeenworkingwiththePlay!frameworkandNashorninanattempttorenderaReduxappl

I've recently been working with the Play! framework and Nashorn in an attempt to render a Redux application. Initially, I had implemented multiple Nashorn engines in a ThreadPoolExecutor and used futures when running engine.eval(). The performance was terrible, I'm assuming due to the high I/O and the blocking future I was using.

我最近一直在玩Play!框架和Nashorn试图渲染Redux应用程序。最初,我在ThreadPoolExecutor中实现了多个Nashorn引擎,并在运行engine.eval()时使用了future。性能很糟糕,我假设由于高I / O和我使用的阻塞未来。

After becoming more familiar with Play! and their async/promise pattern, I attempted to start over with just a single ScriptEngine; per https://stackoverflow.com/a/30159424/5956783, the script engine itself is thread safe, however bindings are not. Here is the class in its entirety:

在熟悉Play之后!和他们的异步/承诺模式,我试图只用一个ScriptEngine重新开始;根据https://stackoverflow.com/a/30159424/5956783,脚本引擎本身是线程安全的,但绑定不是。这是完整的课程:

package services;

import akka.actor.ActorSystem;

import play.libs.F;
import scala.concurrent.ExecutionContext;

import java.io.FileReader;


import javax.inject.Inject;
import javax.inject.Singleton;
import javax.script.*;

@Singleton
public class NashornEngine extends JSEngineAbstract {

    private NashornThread engine;
    private final ActorSystem actorSystem;


    protected class NashornThread {
        private ScriptEngine engine;
        private final ExecutionContext executiOnContext= actorSystem.dispatchers().lookup("js-engine-executor");
        private CompiledScript compiledScript;


        public NashornThread() {
            try {
                String dir = System.getProperty("user.dir");
                this.engine = new ScriptEngineManager(null).getEngineByName("nashorn");
                this.compiledScript = ((Compilable) this.engine).compile(new FileReader(dir + "/public/Javascripts/bundle.js"));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        public ScriptEngine getEngine() {
            return engine;
        }

        public F.Promise getContent(String path, String globalCode) {
            return F.Promise.promise(() -> this.executeMethod(path, globalCode), this.executionContext);
        }

        private String executeMethod(String path, String json) throws ScriptException {
            Bindings newBinding = engine.createBindings();
            try {
                this.compiledScript.eval(newBinding);
                getEngine().setBindings(newBinding, ScriptContext.ENGINE_SCOPE);
                getEngine().eval("var global = this;");
                getEngine().eval("var cOnsole= {log: print, error: print, warn: print};");
                String result = getEngine().eval("App.renderApp('" + path + "', " + json + ")").toString();

                return result;
            } catch(Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }


    @Inject
    public NashornEngine(ActorSystem actorSystem) {
        this.actorSystem = actorSystem;
        this.engine = new NashornThread();
    }

    @Override
    public F.Promise getContent(String path, String globalCode) {
        try {
            F.Promise result = engine.getContent(path, globalCode);

            return result.map((String r) -> r);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

My Javascript application exports an App object with the method renderApp(path, state) visible. This actually does work, but only 16 times (yes, always 16). Starting with iteration 17, I get the following exception and accompanying stack trace:

我的Javascript应用程序导出一个App对象,其方法renderApp(path,state)可见。这确实有效,但只有16次(是的,总是16次)。从迭代17开始,我得到以下异常并伴随着堆栈跟踪:

java.lang.ClassCastException: jdk.nashorn.internal.objects.NativeRegExpExecResult cannot be cast to jdk.nashorn.internal.objects.NativeArray
    at jdk.nashorn.internal.objects.NativeArray.getContinuousArrayDataCCE(NativeArray.java:1900)
    at jdk.nashorn.internal.objects.NativeArray.popObject(NativeArray.java:937)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:660)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:228)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23589$782286AA$\^eval\_.L:22918$L:22920$matchPattern(:23049)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23588$816752AAAAAA$\^eval\_.L:24077$L:24079$matchRouteDeep(:24168)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23587$820262DAA$\^eval\_.L:24077$L:24079$matchRoutes$L:24252$L:24253(:24254)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23586$809060$\^eval\_.L:23848$loopAsync$next(:23869)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23584$808906AAA$\^eval\_.L:23848$loopAsync(:23875)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23583$820189$\^eval\_.L:24077$L:24079$matchRoutes$L:24252(:24253)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23582$819862AAA$\^eval\_.L:24077$L:24079$matchRoutes(:24252)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23580$789440AA$\^eval\_.L:23151$L:23153$useRoutes$L:23209$match(:23239)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23518$847004AA$\^eval\_.L:25026$L:25028$match(:25084)
    at jdk.nashorn.internal.scripts.Script$Recompilation$23468$3872AA$\^eval\_.L:53$renderApp(:147)
    at jdk.nashorn.internal.scripts.Script$23467$\^eval\_.:program(:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:640)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:228)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:446)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:403)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at services.NashornEngine$NashornThread.executeMethod(NashornEngine.java:62)
    at services.NashornEngine$NashornThread.lambda$getContent$0(NashornEngine.java:48)
    at play.core.j.FPromiseHelper$$anonfun$promise$2.apply(FPromiseHelper.scala:36)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
    at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

I am under the impression that creating a new binding with the compiled script would be treated as net-new to the engine, but that doesn't seem to be the case. What, if anything, am I doing wrong here?

我的印象是,使用已编译的脚本创建新绑定将被视为引擎的新网络,但似乎并非如此。如果有的话,我在这里做错了什么?

I have attempted to use an Invocable as well to invoke the method on the App object, but that doesn't make any difference.

我试图使用Invocable来调用App对象上的方法,但这没有任何区别。

EDIT I'm on an 8 core machine with hyper-threading, so that may explain the 16 successful attempts before the failed 17th attempt. Also, I've updated the executeMethod method to below:

编辑我在一台带有超线程的8核机器上,这可以解释在第17次尝试失败之前的16次成功尝试。另外,我已将executeMethod方法更新为:

private String executeMethod(String path, String json) throws ScriptException {
            Bindings newBinding = engine.createBindings();
            try {
                this.compiledScript.eval(newBinding);
                getEngine().eval("var global = this;", newBinding);
                getEngine().eval("var cOnsole= {log: print, error: print, warn: print};", newBinding);
                Object app = getEngine().eval("App", newBinding);
                Invocable invEngine = (Invocable) getEngine();
                String result = invEngine.invokeMethod(app, "renderApp", path, json).toString();
//              String result = getEngine().eval("App.renderApp('" + path + "', " + json + ")", newBinding).toString();

                return result;
            } catch(Exception e) {
                e.printStackTrace();
                return null;
            }
        }

2 个解决方案

#1


1  

Unfortunately you hit a bug in Nashorn. The good news is that it was fixed already, and the fix is available in current early access releases.

不幸的是你遇到了Nashorn的一个bug。好消息是它已经修复,并且修复程序在当前的早期访问版本中可用。

#2


2  

Updating to the latest version of Nashorn, or Java 1.8u76 fixes the issue.

更新到最新版本的Nashorn或Java 1.8u76可以解决此问题。


推荐阅读
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • Android开发实现的计时器功能示例
    本文分享了Android开发实现的计时器功能示例,包括效果图、布局和按钮的使用。通过使用Chronometer控件,可以实现计时器功能。该示例适用于Android平台,供开发者参考。 ... [详细]
  • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
    本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 数组的排序:数组本身有Arrays类中的sort()方法,这里写几种常见的排序方法。(1)冒泡排序法publicstaticvoidmain(String[]args ... [详细]
  • 面向对象之3:封装的总结及实现方法
    本文总结了面向对象中封装的概念和好处,以及在Java中如何实现封装。封装是将过程和数据用一个外壳隐藏起来,只能通过提供的接口进行访问。适当的封装可以提高程序的理解性和维护性,增强程序的安全性。在Java中,封装可以通过将属性私有化并使用权限修饰符来实现,同时可以通过方法来访问属性并加入限制条件。 ... [详细]
  • (三)多表代码生成的实现方法
    本文介绍了一种实现多表代码生成的方法,使用了java代码和org.jeecg框架中的相关类和接口。通过设置主表配置,可以生成父子表的数据模型。 ... [详细]
author-avatar
北辰孤星123
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有