SlideShare a Scribd company logo
1 of 32
Next Step of JavaScript on Java
Takaaki Sugiyama
Software Engineer / Technical Writer
Japan Java User Group
@zinbe
Agenda
1. Why JavaScript on Java
2. History
3. GraalVM JavaScript
4. Compatibility
Why JavaScript on Java
Want to use the powerful library and toolset available
in Java from JavaScript
Want rapid prototyping with JavaScript
Integrate business processes using JavaScript
(Set up a process flow with JavaScript)
Want to develop a combination of services using JavaScript.
JavaScript is one of the most common languages in
the world
What is JavaScript support
JSR 223: Scripting for the Java Platform
JavaScript code could access to Java object
Java program could execute JavaScript code
JDK bundles JavaScript engine
Enable to use the familiar Java API in JavaScript program
Securely execute JavaScript without breaking the Java sandbox
(known as javax.script API)
History of Supporting JavaScript
20181997 2006 2017
Nashorn supported ECMAScript 6
JDK 9 released
Contained Nashorn based on
ECMAScript 5.1
JDK 8 released
Supported javax.script API
Contained Rhino
JDK 6 released
Nashorn was duplicated
JDK 11 released
Developed by Netscape / Mozilla
Rhino was born
20142011
Nashorn was announced
History of Supporting JavaScript
20181997 2006 2017
Nashorn supported ECMAScript 6
JDK 9 released
Contained Nashorn based on
ECMAScript 5.1
JDK 8 released
Supported javax.script API
Contained Rhino
JDK 6 released
Nashorn was duplicated
JDK 11 released
Developed by Netscape / Mozilla
Rhino was born
20142011
Nashorn was announced
Rhino
JavaScript Engine written in Java
Developed by Mozilla Foundation
JDK 6/7 contains Rhino as a default JavaScript Engine
JDK also contains jrunscript command
Support javax.script API
History of Supporting JavaScript
20181997 2006 2017
Nashorn supported ECMAScript 6
JDK 9 released
Contained Nashorn based on
ECMAScript 5.1
JDK 8 released
Supported javax.script API
Contained Rhino
JDK 6 released
Nashorn was duplicated
JDK 11 released
Developed by Netscape / Mozilla
Rhino was born
20142011
Nashorn was announced
Nashorn
JavaScript Engine based on JSR 292 and invokeDynamic
JDK 8+ contains Nashorn as a default JavaScript Engine
Implementation of ECMAScript 5.1/6
jrunscript command was replaced by jjs command
Support javax.script API
Java → JavaScript
public class Main {
public static void main(String[] args) {
ScriptEngine scriptEngine =
new ScriptEngineManager().getEngineByName("nashorn");
try {
scriptEngine.eval(" function sum(a, b) { return a + b }");
int v = (Integer)scriptEngine.eval("sum(21, 22)");
System.out.println(v);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
JavaScript → Java
var now = java.time.LocalDateTime.now();
print("now = " + now);
print("1 day later = " + now.plusDays(1));
print("Truncated To Hours = " +
now.truncatedTo(java.time.temporal.ChronoUnit.HOURS));
JavaScript → Java
load("nashorn:mozilla_compat.js");
importPackage("java.time");
var now = LocalDateTime.now();
print("now = " + now);
print("1 day later = " + now.plusDays(1));
importPackage("java.time.temporal");
print("Truncated To Hours = " +
now.truncatedTo(ChronoUnit.HOURS));
JEP 335: Deprecate the Nashorn JavaScript Engine
Target version: JDK 11
It means this module will be removed in a future release
(still alive in JDK 13)
Annotated with @Deprecated(forRemoval=true)
Contains the jdk.nashorn.api.scripting and jdk.nashorn.api.tree
packages
jdk.scripting.nashorn module
Contains the jjs tool
jdk.scripting.nashorn.shell module
It doesn’t affect the javax.script API
GraalVM JavaScript
(known as GraalJS)
GraalVM Architecture
https://www.graalvm.org/docs/
GraalVM JavaScript
GraalVM includes an JavaScript engine
Provide js command as a commandline interpreter
Compatible to ECMAScript 2019
Support javax.script API
Fully support Node.js
Implemented using Truffle framework
Also support script mode and REPL mode
Java → JavaScript
import org.graalvm.polyglot.*;
public class Main {
public static void main(String[] args) {
try(Engine engine = Engine.create()) {
Source source = Source.create(
"js",
"function sum(a, b) { return a + b }");
Source source2 = Source.create("js", "sum(21, 22)");
try (Context context = Context.newBuilder().engine(engine).build())
{
context.eval(source);
int v = context.eval(source2).asInt();
System.out.println(v);
}
}
}
}
(with polyglot API)
Java → JavaScript
import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
public class Main {
public static void main(String[] args) {
ScriptEngine scriptEngine =
new ScriptEngineManager().getEngineByName("graal.js");
assert scriptEngine instanceof GraalJSScriptEngine;
try {
scriptEngine.eval("function sum(a, b) { return a + b }");
int v = (Integer) scriptEngine.eval("sum(21, 22)");
System.out.println(v);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
(with javax.script API)
When use enable Nashorn compatibility mode,
start Java with -Dpolyglot.js.nashorn-
compat=true
JavaScript → Java
var now = java.time.LocalDateTime.now();
print("now = " + now);
print("1 day later = " + now.plusDays(1));
print("Truncated To Hours = " +
now.truncatedTo(java.time.temporal.ChronoUnit.HOURS));
$ js --jvm javadate.js
Java classes are only available when the engine started with --jvm
flag.
Compatibility
Compatibility with ECMAScript 6
http://kangax.github.io/compat-table/es6/
Compatibility with ECMAScript 2016+
http://kangax.github.io/compat-table/es2016plus/
Compatibility with Nashorn
• Conditional catch clauses
• Function expression closures
• For-each expressions
• Anonymous class-like syntax for new expression
• Anonymous function statements
• Multi-line string literal (like Unix shell’s here-doc)
• Expressions inside string literals with ${expression}
• Back-quote exec expressions
• Shell script style hash comments
Nashorn has some syntax extensions.
$ js --js.syntax-extensions --experimental-options A_SCRIPT
We can use these extensions with --js.syntax-extensions flag
in GraalJS
-scripting mode
only
Compatibility with Nashorn Syntax Extensions
Sample: Function expression closures
$ js closure.js
SyntaxError: closure.js:1:16 Expected { but found x
function sqr(x) x*x;
^
$ js --js.syntax-extensions --experimental-options closure.js
4
function sqr(x) x*x
print(sqr(2));
Compatibility with Nashorn Syntax Extensions
load("nashorn:mozilla_compat.js");
importPackage("java.time");
var now = LocalDateTime.now();
print("now = " + now);
print("1 day later = " + now.plusDays(1));
importPackage("java.time.temporal");
print("Truncated To Hours = " +
now.truncatedTo(ChronoUnit.HOURS));
$ js --jvm --js.nashorn-compat --experimental-options
javadate_import.js
Some functions require --js.nashorn-compat flag to be set.
Compatibility with Nashorn -scripting mode
Sample: Expressions inside string literals with ${expression}
$ js string.js
Hello, ${x}
$ js --js.scripting --js.syntax-extensions --experimental-options
string.js
Hello, World
var x = "World"
var str = "Hello, ${x}"
print(str)
This Nashorn extension requires -scripting mode.
In this case, we have to put --js.scripting flag on GraalJS.
Compatibility of Java Object
Java global property is also available on GraalJS with --jvm mode
Nashorn GraalVM
Java.type ◯ ◯
Java.from ◯ ◯
Java.to ◯ ◯
Java.extend ◯ ◯
Java.super ◯ ◯
Java.synchronized ◯ ◯
Java.asJSONComparible ◯ ×
Java.isJavaObject ◯ ◯
Java.isType ◯ ◯
Java.typeName ◯ ◯
Java.isJavaFunction ◯ ◯
Java.isScriptObject ◯ ◯
Java.isScriptFunction ◯ ◯
Java.addToClasspath × ◯
Compatibility of Java List Element Access
java.util.List elements can be access as array elements on Nashorn
var ArrayList = Java.type("java.util.ArrayList")
var list = new ArrayList()
list.add("Rhino")
list.add("Nashorn")
list.add("GraalJS")
// get by List's get(int) method
print(list.get(0))
print(list.get(1))
print(list.get(2))
// get via indexe access syntax
print(list[0])
print(list[1])
print(list[2])
// prints list.size()
print(list.length); // prints list.size()
Compatibility of Java List Element Access
$ jjs List.js
Rhino
Nashorn
GraalJS
Rhino
Nashorn
GraalJS
3
$ js --jvm --js.nashorn-compat --experimental-options List.js
Rhino
Nashorn
GraalJS
Rhino
Nashorn
GraalJS
3
Nashorn: OK
GraalVM JavaScript: OK
Compatibility of Java Map Element Access
var HashMap = Java.type("java.util.HashMap")
var map = new HashMap()
// map key-value access by get/put method
map.put('js', 'GraalJS')
print(map.get('js'))
// access keys as properties
print(map['js'])
print(map.js)
// assign new key-value pair as 'property-value'
map['language'] = 'java'
print(map.get("language"))
print(map.language)
print(map['language'])
java.util.Map element can be access as property access with keys
Compatibility of Java List Element Access
$ jjs Map.js
GraalJS
GraalJS
GraalJS
java
java
java
$ js --jvm --js.nashorn-compat --experimental-options Map.js
GraalJS
undefined
undefined
null
undefined
undefined
Nashorn: OK
GraalVM JavaScript: NG
Conclusion
Nashorn is already deprecated from JDK 11
GraalVM JavaScript is the best choice as the next
JavaScript engine with Java
GraalVM JavaScript has highly compatibility with Nashorn
Must to check the dependency on Nashorn original
extensions
GraalVM JavaScript performance is good

More Related Content

What's hot

HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOUHOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
Lucas Jellema
 

What's hot (20)

From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0From Spring Framework 5.3 to 6.0
From Spring Framework 5.3 to 6.0
 
Spring batch
Spring batchSpring batch
Spring batch
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOUHOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
HOW AND WHY GRAALVM IS QUICKLY BECOMING RELEVANT FOR YOU
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
An Introduction to WebAssembly
An Introduction to WebAssemblyAn Introduction to WebAssembly
An Introduction to WebAssembly
 
WebAssembly Fundamentals
WebAssembly FundamentalsWebAssembly Fundamentals
WebAssembly Fundamentals
 
Jenkins 101: Getting Started
Jenkins 101: Getting StartedJenkins 101: Getting Started
Jenkins 101: Getting Started
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Introduction to react js
Introduction to react jsIntroduction to react js
Introduction to react js
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
WebAssembly Overview
WebAssembly OverviewWebAssembly Overview
WebAssembly Overview
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
AOT and Native with Spring Boot 3.0
AOT and Native with Spring Boot 3.0AOT and Native with Spring Boot 3.0
AOT and Native with Spring Boot 3.0
 

Similar to JCConf2019: Next Step of JavaScript on Java

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
elliando dias
 

Similar to JCConf2019: Next Step of JavaScript on Java (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
NoSQL and JavaScript: a love story
NoSQL and JavaScript: a love storyNoSQL and JavaScript: a love story
NoSQL and JavaScript: a love story
 
Nashorn
NashornNashorn
Nashorn
 
How to unit test your React/Redux app
How to unit test your React/Redux appHow to unit test your React/Redux app
How to unit test your React/Redux app
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw  est prêt à tuer le classpathSoft-Shake 2016 : Jigsaw  est prêt à tuer le classpath
Soft-Shake 2016 : Jigsaw est prêt à tuer le classpath
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
SpringとGrarlVM Native Image -2019/12-
SpringとGrarlVM Native Image -2019/12-SpringとGrarlVM Native Image -2019/12-
SpringとGrarlVM Native Image -2019/12-
 
Json generation
Json generationJson generation
Json generation
 
Unit Testing your React / Redux app (@BucharestJS)
Unit Testing your React / Redux app (@BucharestJS)Unit Testing your React / Redux app (@BucharestJS)
Unit Testing your React / Redux app (@BucharestJS)
 
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGeneBang-Bang, you have been hacked - Yonatan Levin, KolGene
Bang-Bang, you have been hacked - Yonatan Levin, KolGene
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Nashorn - JavaScript on the JVM - Akhil Arora
Nashorn - JavaScript on the JVM - Akhil AroraNashorn - JavaScript on the JVM - Akhil Arora
Nashorn - JavaScript on the JVM - Akhil Arora
 
Java fx
Java fxJava fx
Java fx
 

Recently uploaded

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

JCConf2019: Next Step of JavaScript on Java

  • 1. Next Step of JavaScript on Java Takaaki Sugiyama Software Engineer / Technical Writer Japan Java User Group @zinbe
  • 2. Agenda 1. Why JavaScript on Java 2. History 3. GraalVM JavaScript 4. Compatibility
  • 3. Why JavaScript on Java Want to use the powerful library and toolset available in Java from JavaScript Want rapid prototyping with JavaScript Integrate business processes using JavaScript (Set up a process flow with JavaScript) Want to develop a combination of services using JavaScript. JavaScript is one of the most common languages in the world
  • 4. What is JavaScript support JSR 223: Scripting for the Java Platform JavaScript code could access to Java object Java program could execute JavaScript code JDK bundles JavaScript engine Enable to use the familiar Java API in JavaScript program Securely execute JavaScript without breaking the Java sandbox (known as javax.script API)
  • 5. History of Supporting JavaScript 20181997 2006 2017 Nashorn supported ECMAScript 6 JDK 9 released Contained Nashorn based on ECMAScript 5.1 JDK 8 released Supported javax.script API Contained Rhino JDK 6 released Nashorn was duplicated JDK 11 released Developed by Netscape / Mozilla Rhino was born 20142011 Nashorn was announced
  • 6. History of Supporting JavaScript 20181997 2006 2017 Nashorn supported ECMAScript 6 JDK 9 released Contained Nashorn based on ECMAScript 5.1 JDK 8 released Supported javax.script API Contained Rhino JDK 6 released Nashorn was duplicated JDK 11 released Developed by Netscape / Mozilla Rhino was born 20142011 Nashorn was announced
  • 7. Rhino JavaScript Engine written in Java Developed by Mozilla Foundation JDK 6/7 contains Rhino as a default JavaScript Engine JDK also contains jrunscript command Support javax.script API
  • 8. History of Supporting JavaScript 20181997 2006 2017 Nashorn supported ECMAScript 6 JDK 9 released Contained Nashorn based on ECMAScript 5.1 JDK 8 released Supported javax.script API Contained Rhino JDK 6 released Nashorn was duplicated JDK 11 released Developed by Netscape / Mozilla Rhino was born 20142011 Nashorn was announced
  • 9. Nashorn JavaScript Engine based on JSR 292 and invokeDynamic JDK 8+ contains Nashorn as a default JavaScript Engine Implementation of ECMAScript 5.1/6 jrunscript command was replaced by jjs command Support javax.script API
  • 10. Java → JavaScript public class Main { public static void main(String[] args) { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn"); try { scriptEngine.eval(" function sum(a, b) { return a + b }"); int v = (Integer)scriptEngine.eval("sum(21, 22)"); System.out.println(v); } catch (ScriptException e) { e.printStackTrace(); } } }
  • 11. JavaScript → Java var now = java.time.LocalDateTime.now(); print("now = " + now); print("1 day later = " + now.plusDays(1)); print("Truncated To Hours = " + now.truncatedTo(java.time.temporal.ChronoUnit.HOURS));
  • 12. JavaScript → Java load("nashorn:mozilla_compat.js"); importPackage("java.time"); var now = LocalDateTime.now(); print("now = " + now); print("1 day later = " + now.plusDays(1)); importPackage("java.time.temporal"); print("Truncated To Hours = " + now.truncatedTo(ChronoUnit.HOURS));
  • 13. JEP 335: Deprecate the Nashorn JavaScript Engine Target version: JDK 11 It means this module will be removed in a future release (still alive in JDK 13) Annotated with @Deprecated(forRemoval=true) Contains the jdk.nashorn.api.scripting and jdk.nashorn.api.tree packages jdk.scripting.nashorn module Contains the jjs tool jdk.scripting.nashorn.shell module It doesn’t affect the javax.script API
  • 16. GraalVM JavaScript GraalVM includes an JavaScript engine Provide js command as a commandline interpreter Compatible to ECMAScript 2019 Support javax.script API Fully support Node.js Implemented using Truffle framework Also support script mode and REPL mode
  • 17. Java → JavaScript import org.graalvm.polyglot.*; public class Main { public static void main(String[] args) { try(Engine engine = Engine.create()) { Source source = Source.create( "js", "function sum(a, b) { return a + b }"); Source source2 = Source.create("js", "sum(21, 22)"); try (Context context = Context.newBuilder().engine(engine).build()) { context.eval(source); int v = context.eval(source2).asInt(); System.out.println(v); } } } } (with polyglot API)
  • 18. Java → JavaScript import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine; public class Main { public static void main(String[] args) { ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("graal.js"); assert scriptEngine instanceof GraalJSScriptEngine; try { scriptEngine.eval("function sum(a, b) { return a + b }"); int v = (Integer) scriptEngine.eval("sum(21, 22)"); System.out.println(v); } catch (ScriptException e) { e.printStackTrace(); } } } (with javax.script API) When use enable Nashorn compatibility mode, start Java with -Dpolyglot.js.nashorn- compat=true
  • 19. JavaScript → Java var now = java.time.LocalDateTime.now(); print("now = " + now); print("1 day later = " + now.plusDays(1)); print("Truncated To Hours = " + now.truncatedTo(java.time.temporal.ChronoUnit.HOURS)); $ js --jvm javadate.js Java classes are only available when the engine started with --jvm flag.
  • 21. Compatibility with ECMAScript 6 http://kangax.github.io/compat-table/es6/
  • 22. Compatibility with ECMAScript 2016+ http://kangax.github.io/compat-table/es2016plus/
  • 23. Compatibility with Nashorn • Conditional catch clauses • Function expression closures • For-each expressions • Anonymous class-like syntax for new expression • Anonymous function statements • Multi-line string literal (like Unix shell’s here-doc) • Expressions inside string literals with ${expression} • Back-quote exec expressions • Shell script style hash comments Nashorn has some syntax extensions. $ js --js.syntax-extensions --experimental-options A_SCRIPT We can use these extensions with --js.syntax-extensions flag in GraalJS -scripting mode only
  • 24. Compatibility with Nashorn Syntax Extensions Sample: Function expression closures $ js closure.js SyntaxError: closure.js:1:16 Expected { but found x function sqr(x) x*x; ^ $ js --js.syntax-extensions --experimental-options closure.js 4 function sqr(x) x*x print(sqr(2));
  • 25. Compatibility with Nashorn Syntax Extensions load("nashorn:mozilla_compat.js"); importPackage("java.time"); var now = LocalDateTime.now(); print("now = " + now); print("1 day later = " + now.plusDays(1)); importPackage("java.time.temporal"); print("Truncated To Hours = " + now.truncatedTo(ChronoUnit.HOURS)); $ js --jvm --js.nashorn-compat --experimental-options javadate_import.js Some functions require --js.nashorn-compat flag to be set.
  • 26. Compatibility with Nashorn -scripting mode Sample: Expressions inside string literals with ${expression} $ js string.js Hello, ${x} $ js --js.scripting --js.syntax-extensions --experimental-options string.js Hello, World var x = "World" var str = "Hello, ${x}" print(str) This Nashorn extension requires -scripting mode. In this case, we have to put --js.scripting flag on GraalJS.
  • 27. Compatibility of Java Object Java global property is also available on GraalJS with --jvm mode Nashorn GraalVM Java.type ◯ ◯ Java.from ◯ ◯ Java.to ◯ ◯ Java.extend ◯ ◯ Java.super ◯ ◯ Java.synchronized ◯ ◯ Java.asJSONComparible ◯ × Java.isJavaObject ◯ ◯ Java.isType ◯ ◯ Java.typeName ◯ ◯ Java.isJavaFunction ◯ ◯ Java.isScriptObject ◯ ◯ Java.isScriptFunction ◯ ◯ Java.addToClasspath × ◯
  • 28. Compatibility of Java List Element Access java.util.List elements can be access as array elements on Nashorn var ArrayList = Java.type("java.util.ArrayList") var list = new ArrayList() list.add("Rhino") list.add("Nashorn") list.add("GraalJS") // get by List's get(int) method print(list.get(0)) print(list.get(1)) print(list.get(2)) // get via indexe access syntax print(list[0]) print(list[1]) print(list[2]) // prints list.size() print(list.length); // prints list.size()
  • 29. Compatibility of Java List Element Access $ jjs List.js Rhino Nashorn GraalJS Rhino Nashorn GraalJS 3 $ js --jvm --js.nashorn-compat --experimental-options List.js Rhino Nashorn GraalJS Rhino Nashorn GraalJS 3 Nashorn: OK GraalVM JavaScript: OK
  • 30. Compatibility of Java Map Element Access var HashMap = Java.type("java.util.HashMap") var map = new HashMap() // map key-value access by get/put method map.put('js', 'GraalJS') print(map.get('js')) // access keys as properties print(map['js']) print(map.js) // assign new key-value pair as 'property-value' map['language'] = 'java' print(map.get("language")) print(map.language) print(map['language']) java.util.Map element can be access as property access with keys
  • 31. Compatibility of Java List Element Access $ jjs Map.js GraalJS GraalJS GraalJS java java java $ js --jvm --js.nashorn-compat --experimental-options Map.js GraalJS undefined undefined null undefined undefined Nashorn: OK GraalVM JavaScript: NG
  • 32. Conclusion Nashorn is already deprecated from JDK 11 GraalVM JavaScript is the best choice as the next JavaScript engine with Java GraalVM JavaScript has highly compatibility with Nashorn Must to check the dependency on Nashorn original extensions GraalVM JavaScript performance is good

Editor's Notes

  1. Nín hǎo. (你好) Wǒ jiào shān shān guì zhān. (我叫杉山貴章) I studied Chinese when I was a collage student. But I’m sorry, I remember just this two-sentence. My name is Takaaki Sugiyama. I am a board member of the Japan Java User Group. Usually, I’m developing full managed systems for some customers in Japan. Java (Of course), JavaScript, Python, so on. In our systems, we combine several languages as good. So, my talk theme is JavaScript support on Java.
  2. This is the agenda.
  3. Why is JavaScript support is important for Java systems? Because JavaScript is one of the most common programming languages all over the world. It means that there are a lot of developer who have much experience and know-how. As a JavaScript programmer, we want to use powerful Java libraries. As a Java programmer, sometimes, JavaScript may be better for rapid development. To be honest, we want to choose the best of both languages. (As like cherry-picking.)
  4. What means JavaScript support on Java? There is a standard specification in JCP about script language support. It's known as javax.script API. It is a member of Java SE from Java 6. The targets of this JSR are not only JavaScript. But actually, the main target is JavaScript. With this JSR, we can access Java objects from JavaScript code. And also execute JavaScript code in Java program. In addition, JDK bundles a default JavaScript engine.
  5. This is the history of JavaScript supporting on standard Java platform.
  6. JDK’s JavaScript support started from JDK 6. It contains javax.script API and bundles Rhino JavaScript Engine.
  7. Rhino was a Java based JavaScript engine developed by Mozilla Foundation. Rhino provided supporting javax.script API and jrunscript command.
  8. On JDK 8, Rhino replaced by Nashorn.
  9. Nashorn is another JavaScript engine based on invokeDynamic JVM method invocation. In addition, Nashorn implements ECMAScript 5.1 and 6. jrunscript command was replaced by jjs command based on Nashorn.
  10. This is an example that executes JavaScript code in the Java program using javax.script API. ScriptEngine and ScriptEngineManager are provided by javax.script API. But the concrete classes are provided by Nashorn.
  11. This is an example that uses Java classes on the JavaScript code.
  12. This is another example that has the same behavior. Nashorn has some extensions for interop with Java. Nashorn is a powerful and useful tool.
  13. However, there is a sad news. OpenJDK team decided to deprecate Nashorn on JDK 11. Actually, there are two target modules. They contain the implementation of javax.script API and jjs command-line tool. The important thing, this deprecation doesn't affect the javax.script API itself. We can continue to use this API. However, we must choose the alternative JavaScript engine.
  14. The best alternative is GraalVM JavaScript. It's well known as GraalJS.
  15. GraalVM is a polyglot virtual machine developed by Oracle. It supports several languages include JavaScript.
  16. GraalVM includes an JavaScript Engine as default. It is compatible to recent ECMAScript. And also support javax.script API. And provide a commandline interpreter named ”js”. In addition, GraalJS has fully support Node.js.
  17. This is an example that executes JavaScript code in the Java program using GraalVM’s polyglot API. It is different from javax.script API. The Engine class, Source class, and Context class are provided by the polyglot API.
  18. You can also use javax.script API. In this case, specify “graal.js” as the engine name. This mode is supported for just backward compatibility. So, polyglot API should be preferred whenever possible. Because the type of result is clearer than javax.script API.
  19. This is an example that uses Java classes on JavaScript code. If you want to use Java classes, --jvm flag is neccessary when starting the engine.
  20. I will talk about the compatibility of GraalVM JavaScript.
  21. This is the rate of compatibility with ECMAScript 6. GraalVM covers 98% of the basic feature. Nashorn for JDK 10 covers only 28%.
  22. Regarding more recent ECMAScript, GraalVM covers 97% feature. It is better than major browser except for Google Chrome.
  23. Of course, we have to care about compatibility with Nashorn for migration. Nashorn has some useful syntax extensions. Like this. We can still use these extensions with –js.stntax-extensions flag in GraalJS. But this mode is an experimental feature, so –experimental-options flag also needs with this.
  24. This is an example of using a Nashorn syntax extension. Without this flag, the interpreter throws a syntax error.
  25. This is another example. Some functions require a Nashorn-compat mode flag.
  26. This example shows a Nashorn extension with -scripting mode. For Nashorn scripting mode, you have to put –js.scripting flag on GraalJS.
  27. Nashorn provides "Java" global property for interrop with Java and JavaScript objects. GraalVM also provides same property. But it is little bit different from Nashorn’s one. Like this.
  28. Nashorn has a syntax sugar for List element access. We can access List elements as array elements.
  29. GraalJS also provides this syntax sugar.
  30. Nashorn has similer syntax sugar for Map elements sccess.
  31. However, GraalJS doesn’t support it, yet.
  32. Conclusion. We have to migrate to altenative JavaScript Engine from Nashorn. GraalJS is very good. However, you must check the compatibility carefully. Especially, you are using some Nashorn original extensions. Because the compatibility is not perfect.