Home  >  Article  >  Java  >  Detailed explanation of examples of Nashorn, a new feature of Java

Detailed explanation of examples of Nashorn, a new feature of Java

零下一度
零下一度Original
2017-06-17 14:04:091815browse

This article mainly introduces the relevant information of Nashorn, a new feature of Java. Friends who need it can refer to it

What is Nashorn

Nashorn, pronounced "nass-horn", is the name of a German tank during World War II. It is also a new generation of javascript engine for java8 - replacing the old and slow Rhino, compliant with ECMAScript-262 version 5.1 language specification. You may think that JavaScript runs in the web browser and provides various dom operations on HTML, but Nashorn does not support browser DOM objects. This is a point to note.

About getting started with Nashorn

There are mainly two aspects, the jjs tool and the API under the javax.script package:

jjs comes under java_home/bin. As an example, let us create a func.js with the following content:


##

function f() {
return 1;
};
print( f() + 1 );

Run this file and use this file as The parameters are passed to jjs


jjs func.js

Output result: 2

The other aspect is javax.script, which is also the remaining API from Rhino


ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName( "JavaScript" );
System.out.println( engine.getClass().getName() );
System.out.println( "Result:" + engine.eval( "function f() { return 1; }; f() + 1;" ) );

The output is as follows:


jdk.nashorn.api.scripting.NashornScriptEngine
Result: 2
Nashorn VS Rhino

It is nothing new for javascript to run on jvm. Rhino already existed in jdk6. But why is Rhino replaced now? The official explanation is that Rhino is too slow compared to other javascript engines (such as Google's V8). To transform Rhino, it is better to rewrite it. Since performance is a highlight of Nashorn, let’s test the performance comparison below. In order to compare the performance between the two, you need to use Esprima, an ECMAScript parsing framework. Use it to parse the uncompressed version of jquery (about 268kb) and test the core. The code is as follows:


static void rhino(String parser, String code) {
    String source = "speedtest";
    int line = 1;
    Context context = Context.enter();
    context.setOptimizationLevel(9);
    try {
      Scriptable scope = context.initStandardObjects();
      context.evaluateString(scope, parser, source, line, null);
      ScriptableObject.putProperty(scope, "$code", Context.javaToJS(code, scope));
      Object tree = new Object();
      Object tokens = new Object();
      for (int i = 0; i < RUNS; ++i) {
        long start = System.nanoTime();
        tree = context.evaluateString(scope, "esprima.parse($code)", source, line, null);
        tokens = context.evaluateString(scope, "esprima.tokenize($code)", source, line, null);
        long stop = System.nanoTime();
        System.out.println("Run #" + (i + 1) + ": " + Math.round((stop - start) / 1e6) + " ms");
      }
    } finally {
      Context.exit();
      System.gc();
    }
  }
  static void nashorn(String parser, String code) throws ScriptException,NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn");
    engine.eval(parser);
    Invocable inv = (Invocable) engine;
    Object esprima = engine.get("esprima");
    Object tree = new Object();
    Object tokens = new Object();
    for (int i = 0; i < RUNS; ++i) {
      long start = System.nanoTime();
      tree = inv.invokeMethod(esprima, "parse", code);
      tokens = inv.invokeMethod(esprima, "tokenize", code);
      long stop = System.nanoTime();
      System.out.println("Run #" + (i + 1) + ": " + Math.round((stop - start) / 1e6) + " ms");
    }
    // System.out.println("Data is " + tokens.toString() + " and " + tree.toString());
  }

As can be seen from the code, the test program will execute Esprima's parse and tokenize to run the content of the test file. Rhino and Nashorn will execute it 30 times respectively. At the beginning, Rhino took 1726 ms and slowly accelerated, and finally stabilized at around 950ms. Nashorn had another feature. The first run took 3682ms, but it quickly accelerated after warming up, and finally stabilized at 175ms for each run, as shown below. As shown

nashorn first compiles the javascript code into java bytecode, and then runs it on the jvm. The bottom layer also uses the invokedynamic command to execute, so the running speed is very fast.

Why use java to implement javascript

This is also the focus of most students. The point of view I agree with is:

1. Mature GC

2. Mature JIT compiler

3. Multi-thread support

4. Rich standard library and third-party library

In general, it makes full use of the existing resources of the Java platform.

Summary

The new Rhino can be said to be a rhino-style chariot, much faster than Rhino. As a high-performance javascript running environment, Nashorn has many possibilities.

For example, Avatar.js relies on Nashorn to support the

Node.js programming model on the JVM, and also adds other new features, such as using a built-in load The balancer implements multiple event loops and uses multi-threading to implement a lightweight messaging mechanism; Avatar also provides a Model-Store, a pure JavaScript ORM framework based on JPA.

Another way to leverage Nashorn in the enterprise is scripting. Compared with usually using shell scripts such as Linux, we can now

use Javascript scripts to interact with Java. Even use Nashorn to monitor server health through the REST interface.

The above is the detailed content of Detailed explanation of examples of Nashorn, a new feature of Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn