SlideShare una empresa de Scribd logo
1 de 33
Rory Preddy
JavaScript on the VM
“Any application that can be written in JavaScript, will eventually be
written in JavaScript”
- Jeff Atwood (founder, stackoverflow.com)
In the Beginning - JavaScript
• Developed by Netscape as a portable version of
Java offering a lightweight interpreted language
• Developed under the name Mocha, officially
released as LiveScript in September 1995,
• Renamed JavaScript in December 1995 as a
marketing ploy to leverage off Java's popularity
• Even reserved Java’s keywords
• Standardized by ECMA International
JavaScript/Java Timeline
1.3 1.4 5.0 6 7 8
Rhino
(Separate download)
invokeDynamic
Nashorn
JDK with Scripting
and built in Rhino
Rhino
In the Beginning - Rhino
• In 1997 Netscape wanted a browser written fully in
Java and so it needed an implementation of
JavaScript written in Java.
• Code named "Javagator", project was canned but
engine lived on
• Compiles JavaScript code to Java bytecodes in
either Interpreted or generated Java class files.
• Suffers from:
• Slow compile time
• Memory leaks
• Very unsecure!!!
Using Rhino - Command line and REPL
• jrunscript -e "print('hello world')“
• jrunscript -l js -f helloWorld.js
• jrunscript
js> print('Hello Worldn');
>>Hello World
Using Scripting API - background
• “javax.script” package
• Use any JSR-223 compliant scripting language.
• Java SE 6 & 7 include Scripting API and Mozilla
Rhino as default engine
• Extensive list of available engines: Python, Ruby,
PHP, Groovy …
Script API Basics
1) Create a ScriptEngineManager object.
ScriptEngineManager factory = new ScriptEngineManager();
2) Get a ScriptEngine object from the manager.
ScriptEngine engine = factory.getEngineByName("JavaScript");
3) Evaluate script using the ScriptEngine's eval methods.
engine.eval("print('Hello, World')");
Invoking Script Functions and Methods
String script = "function hello(name) {" +
" return 'Hello, ' + name; " +
}";
engine.eval(script);
Invocable inv = (Invocable) engine;
String val = (String) inv.invokeFunction("hello", "BBD!!");
System.out.println(val);
>>Hello, BBD!!
Binding Java objects into script space
Bindings bindings = new SimpleBindings();
bindings.put("author", new Person("Rory", "Preddy", 34));
engine.eval("print('Name:' + author.name)", bindings);
>>Name: Rory
Callbacks
…
engine.put("cb", new JsCallback());
engine.eval("println('Doing something in javascript here first');" +
"cb.apply('bar');");
}
public void apply(String s){
System.out.println("Back in java code here: " + s);
}
…
>>Doing something in javascript here first
>>Back in java code here: bar
Implementing Java Interfaces by Scripts
String script =
"function run() { "
+ "println('run called'); "
+ "}";
engine.eval(script);
Runnable r = ((Invocable) engine).getInterface(Runnable.class);
new Thread(r).start();
>>run called
Java Interfaces in JavaScript
var r = new java.lang.Runnable() {
run: function() {
print("running...n");
}
};
var th = new java.lang.Thread(r);
th.start();
>>running…
Compiling
engine.put("counter", 0);
Compilable compEngine = (Compilable) engine;
CompiledScript script = compEngine.compile(
“ function count(){
counter=counter+1;
return counter;
};
count();");
System.out.println(script.eval());
System.out.println(script.eval());
…
>>1.0
>>2.0
Compiling with Rhino
cat test.js
java.lang.System.out.println("hi, mom!");
java org.mozilla.javascript.tools.jsc.Main test.js
ls *.class
test.class
java test
>>hi, mom!
Optimization
-1
Interpretive mode is always used. No class files are generated,
0
Basic Compilation. No optimizations are performed. The compiler runs fastest in this
mode, but the generated byte code is less efficient
1-9
All optimizations are performed. Java Class Files generated
• Rhino optimizer not standard with JDK
• Runtime optimization of compilation can be set from -1 to 9
Nashorn
InvokeDynamic
Opcode Usage
Invokestatic For static methods
Invokevirtual For non-private instance methods
Invokespecial For private instance
Invokeinterface For the receiver that implements the interface
Bytecode operations that were available before JDK version 7:
InvokeStatic
• JavaScript is dynamic
– Things can change at runtime
• For example, what is the type of:
var x = 500000;
• x *= 500000; And now?
The challenge
• Based on an experimental project, the Da
Vinci Machine
• Adds two new concepts to the JVM:
– invokedynamic bytecode instruction
– MethodHandles
• The first bytecode extension since 1999!
Enter JSR 292
InvokeDynamic
Nashorn
• Default script Engine in Java 8
• NO COMILATION! - Compiles JavaScript
directly into byte code
• 20x faster than uncompiled Rhino
• Better typing
• Smaller footprint
• 100% compliant with ECMA 5.1
• Java 9 has Partial ECMA 6!
> jjs
jjs> var x = 10, y = 20;
jjs> x + y;
>>30
Or
> jjs example.js
Nashorn- Command Line
Rhino VS Nashorn - Types
…
engine.eval("function test() { return 1; };");
Object result = ((Invocable)engine).invokeFunction("test");
System.out.println(result.getClass().getName());
//Rhino output
>>>java.lang.Double
// Nashorn output
>>>java.lang.Integer
Lambdas in Nashorn
var list = java.util.Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
var odd = list.stream().filter(function(i) {
return i % 2 == 0;
});
odd.forEach(function(i) {
print(">>> " + i);
});
>>> 2
>>> 4
>>> 6
>>> 8
Nashorn Vs Rhino
Why you care
• Server-side JavaScript
• Leverage Existing
JavaScript Libraries
• Cross Platform scripting –
Rhino runs on Android
• Fast performance with
Nashorn
• Leverage some vNode
Libraries with Nashorn
Why Oracle cares
• Atwood’s law
• Node.js
– A real threat to Java’s
server-side growth
• Let developers handle
typing with
invokedynamic
– Jruby, Jython
Summary – JavaScript Why bother?
Demo
Demo overview
• Credit card validation
• Fibonacci numbers
• Interest calculation
• Groovy Examples
https://github.com/roryp/nashorn
Java 9 - ECMA 6 Support!

Más contenido relacionado

La actualidad más candente

Java/Spring과 Node.js의 공존 시즌2
Java/Spring과 Node.js의 공존 시즌2Java/Spring과 Node.js의 공존 시즌2
Java/Spring과 Node.js의 공존 시즌2동수 장
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)Tomer Gabel
 
Node.js tutoria for beginner
Node.js tutoria for beginnerNode.js tutoria for beginner
Node.js tutoria for beginnerManinder Singh
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking ioAmy Hua
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
Javascript Bundling and modularization
Javascript Bundling and modularizationJavascript Bundling and modularization
Javascript Bundling and modularizationstbaechler
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 

La actualidad más candente (20)

Java/Spring과 Node.js의 공존 시즌2
Java/Spring과 Node.js의 공존 시즌2Java/Spring과 Node.js의 공존 시즌2
Java/Spring과 Node.js의 공존 시즌2
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)Nashorn: JavaScript that doesn’t suck (ILJUG)
Nashorn: JavaScript that doesn’t suck (ILJUG)
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node.js tutoria for beginner
Node.js tutoria for beginnerNode.js tutoria for beginner
Node.js tutoria for beginner
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking io
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Javascript Bundling and modularization
Javascript Bundling and modularizationJavascript Bundling and modularization
Javascript Bundling and modularization
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 

Similar a Nashorn

JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An IntroductionNirvanic Labs
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesCharles Nutter
 
Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn't suck - Tomer Gabel, WixNashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn't suck - Tomer Gabel, WixCodemotion Tel Aviv
 
(2018) Webpack Encore - Asset Management for the rest of us
(2018) Webpack Encore - Asset Management for the rest of us(2018) Webpack Encore - Asset Management for the rest of us
(2018) Webpack Encore - Asset Management for the rest of usStefan Adolf
 
Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)Ontico
 
Docker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionBrennan Saeta
 
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many LanguagesJava ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languageselliando dias
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaChristopher Bartling
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Ryan Weaver
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Ryan Cuprak
 
Java 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
Java 8: Nashorn & avatar.js di Enrico Risa al JUG RomaJava 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
Java 8: Nashorn & avatar.js di Enrico Risa al JUG RomaVitalij Zadneprovskij
 
Javantura 2014 - Java 8 JavaScript Nashorn
Javantura 2014 - Java 8 JavaScript NashornJavantura 2014 - Java 8 JavaScript Nashorn
Javantura 2014 - Java 8 JavaScript NashornMiroslav Resetar
 
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 2015jbandi
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
Supercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicSupercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicIan Robertson
 

Similar a Nashorn (20)

JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn't suck - Tomer Gabel, WixNashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix
 
(2018) Webpack Encore - Asset Management for the rest of us
(2018) Webpack Encore - Asset Management for the rest of us(2018) Webpack Encore - Asset Management for the rest of us
(2018) Webpack Encore - Asset Management for the rest of us
 
Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)
 
Everything as a code
Everything as a codeEverything as a code
Everything as a code
 
Docker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline Execution
 
Java ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many LanguagesJava ScriptingJava Scripting: One VM, Many Languages
Java ScriptingJava Scripting: One VM, Many Languages
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
 
Java 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
Java 8: Nashorn & avatar.js di Enrico Risa al JUG RomaJava 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
Java 8: Nashorn & avatar.js di Enrico Risa al JUG Roma
 
Javantura Zagreb 2014 - Nashorn - Miroslav Rešetar
Javantura Zagreb 2014 - Nashorn - Miroslav RešetarJavantura Zagreb 2014 - Nashorn - Miroslav Rešetar
Javantura Zagreb 2014 - Nashorn - Miroslav Rešetar
 
Javantura 2014 - Java 8 JavaScript Nashorn
Javantura 2014 - Java 8 JavaScript NashornJavantura 2014 - Java 8 JavaScript Nashorn
Javantura 2014 - Java 8 JavaScript Nashorn
 
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
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Supercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicSupercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamic
 
Play framework
Play frameworkPlay framework
Play framework
 

Más de Rory Preddy

Programming for accessibility
Programming for accessibilityProgramming for accessibility
Programming for accessibilityRory Preddy
 
Whats new in .net for 2019
Whats new in .net for 2019Whats new in .net for 2019
Whats new in .net for 2019Rory Preddy
 
Whats new in .NET for 2019
Whats new in .NET for 2019Whats new in .NET for 2019
Whats new in .NET for 2019Rory Preddy
 
Getting started with Firebase
Getting started with FirebaseGetting started with Firebase
Getting started with FirebaseRory Preddy
 
Whats new in Java 9,10,11,12
Whats new in Java 9,10,11,12Whats new in Java 9,10,11,12
Whats new in Java 9,10,11,12Rory Preddy
 
AWS for Java Developers workshop
AWS for Java Developers workshopAWS for Java Developers workshop
AWS for Java Developers workshopRory Preddy
 
Java 2018 certifications
Java 2018 certificationsJava 2018 certifications
Java 2018 certificationsRory Preddy
 
AWS Transcribe and Comprehend
AWS Transcribe and ComprehendAWS Transcribe and Comprehend
AWS Transcribe and ComprehendRory Preddy
 
BDD with Mockito
BDD with MockitoBDD with Mockito
BDD with MockitoRory Preddy
 
Up and Running with Kubernetes
Up and Running with KubernetesUp and Running with Kubernetes
Up and Running with KubernetesRory Preddy
 
Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Rory Preddy
 
AWS and Serverless with Alexa
AWS and Serverless with AlexaAWS and Serverless with Alexa
AWS and Serverless with AlexaRory Preddy
 
AWS for the Java Developer
AWS for the Java DeveloperAWS for the Java Developer
AWS for the Java DeveloperRory Preddy
 
BDD - Keep love alive
BDD - Keep love aliveBDD - Keep love alive
BDD - Keep love aliveRory Preddy
 

Más de Rory Preddy (19)

Programming for accessibility
Programming for accessibilityProgramming for accessibility
Programming for accessibility
 
Whats new in .net for 2019
Whats new in .net for 2019Whats new in .net for 2019
Whats new in .net for 2019
 
Whats new in .NET for 2019
Whats new in .NET for 2019Whats new in .NET for 2019
Whats new in .NET for 2019
 
Getting started with Firebase
Getting started with FirebaseGetting started with Firebase
Getting started with Firebase
 
Whats new in Java 9,10,11,12
Whats new in Java 9,10,11,12Whats new in Java 9,10,11,12
Whats new in Java 9,10,11,12
 
AWS for Java Developers workshop
AWS for Java Developers workshopAWS for Java Developers workshop
AWS for Java Developers workshop
 
Java modules
Java modulesJava modules
Java modules
 
Java 2018 certifications
Java 2018 certificationsJava 2018 certifications
Java 2018 certifications
 
AWS Transcribe and Comprehend
AWS Transcribe and ComprehendAWS Transcribe and Comprehend
AWS Transcribe and Comprehend
 
BDD with Mockito
BDD with MockitoBDD with Mockito
BDD with Mockito
 
Up and Running with Kubernetes
Up and Running with KubernetesUp and Running with Kubernetes
Up and Running with Kubernetes
 
Dockercompose
DockercomposeDockercompose
Dockercompose
 
Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5Functional Reactive Endpoints using Spring 5
Functional Reactive Endpoints using Spring 5
 
AWS and Serverless with Alexa
AWS and Serverless with AlexaAWS and Serverless with Alexa
AWS and Serverless with Alexa
 
AWS for the Java Developer
AWS for the Java DeveloperAWS for the Java Developer
AWS for the Java Developer
 
Vs java (1)
Vs java (1)Vs java (1)
Vs java (1)
 
Polyglot
PolyglotPolyglot
Polyglot
 
BDD - Keep love alive
BDD - Keep love aliveBDD - Keep love alive
BDD - Keep love alive
 
Kotlin
KotlinKotlin
Kotlin
 

Último

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-...Steffen Staab
 
%+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
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
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-learnAmarnathKambale
 
%+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
 
%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 tembisamasabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
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 AidPhilip Schwarz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
%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 tembisamasabamasaba
 
%+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
 

Último (20)

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-...
 
%+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...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
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
 
%+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 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
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+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...
 

Nashorn

  • 2. “Any application that can be written in JavaScript, will eventually be written in JavaScript” - Jeff Atwood (founder, stackoverflow.com)
  • 3.
  • 4. In the Beginning - JavaScript • Developed by Netscape as a portable version of Java offering a lightweight interpreted language • Developed under the name Mocha, officially released as LiveScript in September 1995, • Renamed JavaScript in December 1995 as a marketing ploy to leverage off Java's popularity • Even reserved Java’s keywords • Standardized by ECMA International
  • 5. JavaScript/Java Timeline 1.3 1.4 5.0 6 7 8 Rhino (Separate download) invokeDynamic Nashorn JDK with Scripting and built in Rhino
  • 7. In the Beginning - Rhino • In 1997 Netscape wanted a browser written fully in Java and so it needed an implementation of JavaScript written in Java. • Code named "Javagator", project was canned but engine lived on • Compiles JavaScript code to Java bytecodes in either Interpreted or generated Java class files. • Suffers from: • Slow compile time • Memory leaks • Very unsecure!!!
  • 8. Using Rhino - Command line and REPL • jrunscript -e "print('hello world')“ • jrunscript -l js -f helloWorld.js • jrunscript js> print('Hello Worldn'); >>Hello World
  • 9. Using Scripting API - background • “javax.script” package • Use any JSR-223 compliant scripting language. • Java SE 6 & 7 include Scripting API and Mozilla Rhino as default engine • Extensive list of available engines: Python, Ruby, PHP, Groovy …
  • 10. Script API Basics 1) Create a ScriptEngineManager object. ScriptEngineManager factory = new ScriptEngineManager(); 2) Get a ScriptEngine object from the manager. ScriptEngine engine = factory.getEngineByName("JavaScript"); 3) Evaluate script using the ScriptEngine's eval methods. engine.eval("print('Hello, World')");
  • 11. Invoking Script Functions and Methods String script = "function hello(name) {" + " return 'Hello, ' + name; " + }"; engine.eval(script); Invocable inv = (Invocable) engine; String val = (String) inv.invokeFunction("hello", "BBD!!"); System.out.println(val); >>Hello, BBD!!
  • 12. Binding Java objects into script space Bindings bindings = new SimpleBindings(); bindings.put("author", new Person("Rory", "Preddy", 34)); engine.eval("print('Name:' + author.name)", bindings); >>Name: Rory
  • 13. Callbacks … engine.put("cb", new JsCallback()); engine.eval("println('Doing something in javascript here first');" + "cb.apply('bar');"); } public void apply(String s){ System.out.println("Back in java code here: " + s); } … >>Doing something in javascript here first >>Back in java code here: bar
  • 14. Implementing Java Interfaces by Scripts String script = "function run() { " + "println('run called'); " + "}"; engine.eval(script); Runnable r = ((Invocable) engine).getInterface(Runnable.class); new Thread(r).start(); >>run called
  • 15. Java Interfaces in JavaScript var r = new java.lang.Runnable() { run: function() { print("running...n"); } }; var th = new java.lang.Thread(r); th.start(); >>running…
  • 16. Compiling engine.put("counter", 0); Compilable compEngine = (Compilable) engine; CompiledScript script = compEngine.compile( “ function count(){ counter=counter+1; return counter; }; count();"); System.out.println(script.eval()); System.out.println(script.eval()); … >>1.0 >>2.0
  • 17. Compiling with Rhino cat test.js java.lang.System.out.println("hi, mom!"); java org.mozilla.javascript.tools.jsc.Main test.js ls *.class test.class java test >>hi, mom!
  • 18. Optimization -1 Interpretive mode is always used. No class files are generated, 0 Basic Compilation. No optimizations are performed. The compiler runs fastest in this mode, but the generated byte code is less efficient 1-9 All optimizations are performed. Java Class Files generated • Rhino optimizer not standard with JDK • Runtime optimization of compilation can be set from -1 to 9
  • 20. InvokeDynamic Opcode Usage Invokestatic For static methods Invokevirtual For non-private instance methods Invokespecial For private instance Invokeinterface For the receiver that implements the interface Bytecode operations that were available before JDK version 7:
  • 22. • JavaScript is dynamic – Things can change at runtime • For example, what is the type of: var x = 500000; • x *= 500000; And now? The challenge
  • 23. • Based on an experimental project, the Da Vinci Machine • Adds two new concepts to the JVM: – invokedynamic bytecode instruction – MethodHandles • The first bytecode extension since 1999! Enter JSR 292
  • 25. Nashorn • Default script Engine in Java 8 • NO COMILATION! - Compiles JavaScript directly into byte code • 20x faster than uncompiled Rhino • Better typing • Smaller footprint • 100% compliant with ECMA 5.1 • Java 9 has Partial ECMA 6!
  • 26. > jjs jjs> var x = 10, y = 20; jjs> x + y; >>30 Or > jjs example.js Nashorn- Command Line
  • 27. Rhino VS Nashorn - Types … engine.eval("function test() { return 1; };"); Object result = ((Invocable)engine).invokeFunction("test"); System.out.println(result.getClass().getName()); //Rhino output >>>java.lang.Double // Nashorn output >>>java.lang.Integer
  • 28. Lambdas in Nashorn var list = java.util.Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); var odd = list.stream().filter(function(i) { return i % 2 == 0; }); odd.forEach(function(i) { print(">>> " + i); }); >>> 2 >>> 4 >>> 6 >>> 8
  • 30. Why you care • Server-side JavaScript • Leverage Existing JavaScript Libraries • Cross Platform scripting – Rhino runs on Android • Fast performance with Nashorn • Leverage some vNode Libraries with Nashorn Why Oracle cares • Atwood’s law • Node.js – A real threat to Java’s server-side growth • Let developers handle typing with invokedynamic – Jruby, Jython Summary – JavaScript Why bother?
  • 31. Demo
  • 32. Demo overview • Credit card validation • Fibonacci numbers • Interest calculation • Groovy Examples https://github.com/roryp/nashorn
  • 33. Java 9 - ECMA 6 Support!

Notas del editor

  1. Tim Berners-Lee on the Principle of Least Power:
  2. abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public
  3. java org.mozilla.javascript.tools.jsc.Main [options] file1.js [file2.js...] where options are: -extends java-class-name Specifies that a java class extending the Java class java-class-name should be generated from the incoming JavaScript source file. Each global function in the source file is made a method of the generated class, overriding any methods in the base class by the same name. -implements java-intf-name Specifies that a java class implementing the Java interface java-intf-name should be generated from the incoming JavaScript source file. Each global function in the source file is made a method of the generated class, implementing any methods in the interface by the same name. -debug -g Specifies that debug information should be generated. May not be combined with optimization at an optLevel greater than zero. -main-method-class className Specify the class name used for main method implementation. The class must have a method matching public static void main(Script sc, String[] args). -nosource Does not save the source in the class file. Functions and scripts compiled this way cannot be decompiled. This option can be used to avoid distributing source or simply to save space in the resulting class file. -o outputFile Writes the class file to outputFile, which should end in .class and must be a writable filename. -d outputDirectory Writes the class file to outputDirectory. -opt optLevel Optimizes at level optLevel, which must be an integer between -1 and 9. See Optimization for more details. If optLevel is greater than zero, -debug may not be specified. -package packageName Specifies the package to generate the class into. The string packageName must be composed of valid identifier characters optionally separated by periods. -version versionNumber Specifies the language version to compile with. The string versionNumber must be one of 100, 110, 120, 130, 140, 150, 160, or 170. See JavaScript Language Versions for more information on language versions.
  4. Chrome is ~15 quicker than compiled Java/Rhino, and ~200 times quicker than interpreted Java/Rhino.
  5. The invokeDynamic instruction was added in Java 7 to allow developers writing their own dynamic languages to decide at runtime how to link code. For static languages like Java and Scala, the compiler decides at compile time which method would be invoked . Unfortunately, for languages which are more dynamic in nature (and JS is a good example) static resolution may not be possible. When we say obj.foo() in Java, either the class of obj has a foo() method or it doesn’t. In a language like JS that will depend on the actual object referenced by obj at runtime - a nightmare scenario for a static compiler. A compile-time approach to linking in this case just doesn't work. But invokeDynamic does. InvokeDynamic enables deferring of linkage back to the writers of the language at run-time, so they can guide the JVM as to which method they would like to call, based on their own language semantics. This is a win-win situation. The JVM gets an actual method to link to, optimize and execute against, and the language makers control its resolution.
  6. A simple invocation to a method starts from a given “Call Site”, A callsite consists of name of the method, the signature (access level, modifiers and return type) and the arguments that are processed by this method The JVM will process this Call Site information and go through a set of operations: It is going to look for that method’s code within memory (Lookup), check if the types involved in the operations match (Type Checking), invokes the actual code (Branch) and then caches the location of that method so, if it is going to be needed again soon, the JVM already knows that memory address and speeds up the process (Cache).
  7. The new “Invokedynamic” bytecode operation allows the JVM to customize how the resources for the Call Site are assembled (dynamically) and also perform a different set of operations within the JVM so the field or method can be accessed (invoked). Instead of the regular Call Site, it integrates bytecode (invokedynamic operation with name and signature) with a bootstrap method, this is the component that will connect the Call Site with the “Method Handle”, once the handle finds the correct way of making this invocation occurs, the JVM will optimize the operation and the invokedynamic bytecode will be attached to the “Target Method” to avoid processing all these steps again. In a scenario where a scripting language that is running within the JVM needs to access a specific function, it is going to initiate the process by providing the bootstrap method with the invokedynamic instructions (name of the function followed by arguments and the return type), the JVM will look for the function within a Method Table (list of functions that are not associated to any object or class) based on the arguments that are defined at runtime (Lookup), once it finds the function, it will perform some language-specific type checking (Type Checking) and then it will finish the bootstrap process connecting the Call Site with the Method Handle so it can be executed (Branch), this connection is performed only once but Call Sites can be connected to new Method Handles.
  8. Behind the scene, Nashorn compiles your JavaScript code into Java bytecodes and run them on the JVM itself. On top of that, Nashorn is taking advantage of invokedynamic instruction (from the Da Vinci Machine Project, part of Java 7) to permit "efficient and flexible execution" in a dynamic environment such as JavaScript
  9. Java 10 Classes Generators Modules Module loaders Tail calls