Is the evaluated function in Nashorn multiple for different flows?

Is it possible to reuse the same Nashorn engine and the same JavaScriptObject, which is the result of evaluating the JS function for all servlet requests, if the function does not modify any common object, but uses only the arguments given with the call? Take a look at the following example:

public class MyServlet extends HttpServlet { private ScriptEngineManager factory; private ScriptEngine engine; private ScriptObjectMirror script; @Override public void init() throws ServletException { try { factory = new ScriptEngineManager(); engine = factory.getEngineByName("nashorn"); script = (ScriptObjectMirror)engine.eval("function(writer) {writer.print('Hello, World!');}"); } catch (ScriptException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { try (PrintWriter writer = res.getWriter()) { script.call(null, writer); writer.close(); } catch (IOException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } } 

Is it thread safe? This is a continuation of Reusing Nashorn ScriptEngine in a Servlet

Edit: I'm not sure what the difference is in this question, but to focus on the more interesting question, under what circumstances, accessing the evaluated js function is a thread, I made all the fields final. So the code:

 public class MyServlet extends HttpServlet { final private ScriptEngineManager factory; final private ScriptEngine engine; final private ScriptObjectMirror script; public MyServlet() { factory = new ScriptEngineManager(); engine = factory.getEngineByName("nashorn"); ScriptObjectMirror _script = null; try { _script = (ScriptObjectMirror) engine.eval("function(writer) {writer.print('Hello, World!');}"); } catch (ScriptException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } script = _script; } @Override public void init() throws ServletException { } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { try (PrintWriter writer = res.getWriter()) { script.call(null, writer); writer.close(); } catch (IOException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } } 
+5
source share
1 answer

None of your instance variables have been safely published , so there is a big no. Also, none of the documentation says that the classes you use are thread safe, so without additional documentation saying differently, you should assume that they are not a safe thread.

The answer is no.

+1
source

Source: https://habr.com/ru/post/1210221/


All Articles