在
javax.script.scriptEngineFactory里面有一种方法
getParameter(Stringkey)。
使用特殊键,
THREADING您可以获得该特定引擎工厂的线程信息。
这个小程序为每个注册的引擎工厂打印出此信息:
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"))); } }}
对于Java 7,它是:
Mozilla Rhino (1.7 release 3 PRERELEASE), ECMAscript (1.8), MULTITHREADED
对于Java 8:
Oracle Nashorn (1.8.0_25), ECMAscript (ECMA - 262 Edition 5.1), null
null表示引擎实现不是线程安全的。
在您的Servlet中,您可以使用
ThreadLocal来为每个线程保留一个单独的引擎,从而允许将引擎重新用于同一线程所服务的后续请求。
public class MyServlet extends HttpServlet { private ThreadLocal<scriptEngine> engineHolder; @Override public void init() throws ServletException { engineHolder = new ThreadLocal<scriptEngine>() { @Override protected scriptEngine initialValue() { return new scriptEngineManager().getEngineByName("nashorn"); } }; } @Override 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); writer.close(); } catch (IOException | scriptException ex) { Logger.getLogger(MyServlet.class.getName()).log(Level.SEVERE, null, ex); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)