Reuse Nashorn ScriptEngine in Servlet

Reuse Nashorn ScriptEngine in Servlet

By : Prateek Madhikar
Date : November 22 2020, 01:01 AM
it should still fix some issue In javax.script.ScriptEngineFactory there is a method getParameter(String key).
With the special key THREADING you get threading information for this specific engine factory.
code :
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

public class ScriptEngineTest {
  public static void main(String[] args) {
    final ScriptEngineManager mgr = new ScriptEngineManager();
    for(ScriptEngineFactory fac: mgr.getEngineFactories()) {
      System.out.println(String.format("%s (%s), %s (%s), %s", fac.getEngineName(),
          fac.getEngineVersion(), fac.getLanguageName(),
          fac.getLanguageVersion(), fac.getParameter("THREADING")));
Mozilla Rhino (1.7 release 3 PRERELEASE), ECMAScript (1.8), MULTITHREADED
Oracle Nashorn (1.8.0_25), ECMAScript (ECMA - 262 Edition 5.1), null
public class MyServlet extends HttpServlet {

  private ThreadLocal<ScriptEngine> engineHolder;

  public void init() throws ServletException {
    engineHolder = new ThreadLocal<ScriptEngine>() {
      protected ScriptEngine initialValue() {
        return new ScriptEngineManager().getEngineByName("nashorn");

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try (PrintWriter writer = res.getWriter()) {
      ScriptContext newContext = new SimpleScriptContext();
      newContext.setBindings(engineHolder.get().createBindings(), ScriptContext.ENGINE_SCOPE);
      Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
      engineScope.put("writer", writer);
      Object value = engineHolder.get().eval("writer.print('Hello, World!');", engineScope);
    } catch (IOException | ScriptException ex) {
      Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex);

Share : facebook icon twitter icon
ScriptEngineManager and ScriptEngine can not be loaded in Karaf OSGi (Nashorn not found)

ScriptEngineManager and ScriptEngine can not be loaded in Karaf OSGi (Nashorn not found)

By : N. Fougere
Date : March 29 2020, 07:55 AM
it should still fix some issue Go to file etc/config.properties (located inside of Karaf installation), find configuration property org.osgi.framework.bootdelegation and add jdk.nashorn.* to it. Complete configuration will be like this:
code :
Nashorn: concurrent eval with singleton ScriptEngine ? thread safe?

Nashorn: concurrent eval with singleton ScriptEngine ? thread safe?

By : Airc
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further My answer to my own question: I would not use a singleton as described above. Despite some potential threading issues, you likely do not want to destroy the bindings at each request (as it may require re-compiling of scripts). What we ended up doing is creating a pool of Engines and their associated scope Bindings. An engine/binding pair.
At each servlet request we grab an engine/binding pair from the pool, put the request/response into the binding, and then execute the script. There is no threading issues to worry about because a given engine/binding pair is only executed by a single thread at a time. When the request is done, the engine/binding pair is returned to the pool. Seems to work well.
Nashorn ScriptEngine not found/registered at Karaf+Felix (openJDK)

Nashorn ScriptEngine not found/registered at Karaf+Felix (openJDK)

By : Bestzwarat
Date : March 29 2020, 07:55 AM
To fix the issue you can do ScriptEngineManager's default constructor uses the thread context class loader with service loader mechanism. If your thread context class loader does not delegate to the extension class loader, then nashorn or any other engine visible only to extension loader will not be found! There are two solutions:
You can temporarily set the thread context class loader to either extension loader or a loader that delegates to it - just before creating ScriptEngineManager object (and you set reset the old thread context class loader after finding the engine). You can use ClassLoader accepting constructor of ScriptEngineManager ( See also: https://docs.oracle.com/javase/8/docs/api/javax/script/ScriptEngineManager.html#ScriptEngineManager-java.lang.ClassLoader-) by passing an appropriate ClassLoader. Again, you can pass the extension class loader or any loader that delegates to the extension class loader - so that engines visible to extension loader can be found by service loader mechanism.
Make Javas Nashorn ScriptEngine behave like a console

Make Javas Nashorn ScriptEngine behave like a console

By : Su Sue
Date : March 29 2020, 07:55 AM
should help you out The various ScriprtEngine.eval() methods all have a return value. Just somehow stringfy it and print it to the desired output, e.g. STDOUT or ingame console.
Jdk nashorn api ScriptEngine returning undefined

Jdk nashorn api ScriptEngine returning undefined

By : techJunkie
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Because you're not passing any argument to your JavaScript function. runScript should be:
code :
public Object runScript( String v1, String v2, String v3, String v4)
        throws NoSuchMethodException, ScriptException
    return ((JSObject) bindings.get("myFunction")).call(null, v1, v2, v3, v4);
Related Posts Related Posts :
  • Why is it mandatory for ternary operations to return a value?
  • How can I make my listview rows different heights
  • Array declaration trick : Is it bad to use it?
  • Calling different classes with if else statements
  • Free API for speech recognition system
  • Java: Objects in JFrame are messed up
  • Is there a similar of MessageBox of ExtJS in ADF Faces
  • Passing HttpServletResponse in Spring Boot controller method
  • Failed to load libraries: [netty_tcnative_linux_arm_32, netty_tcnative_linux_arm_32_fedora, netty_tcnative_arm_32, netty
  • How to build a small documents storage?
  • Getting pixel position of a text in an image
  • How do I get a list of Methods called from a Class in Eclipse IDE?
  • Convert string to day of week (not exact date)
  • Unable to understand how rounding is working for decimal digits (Java)
  • How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)
  • JTable Renderer not working with RowSorter?
  • From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?
  • jUnit tests work in Eclipse, but fail in ant - java.lang.RuntimeException: Stub
  • How do i add a tooltip to existing gwt Textbox?
  • actor replying to non-actor
  • Google Cloud Messaging - server connection
  • Which classes are unmodifiable and cannot be intrumented and is there a way to bypass it?
  • Java & Jersey 1.17: Custom default response headers
  • Java rounding error
  • Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?
  • Arquillian test class variables lose value
  • java.util.ConcurrentModificationException while inserting in ArrayList
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org