SlideShare uma empresa Scribd logo
1 de 32
Nashorn: JavaScript
that doesn’t suck
Tomer Gabel, Wix
ILJUG, April 2014
Agenda
• History
• Features
• Behind the scenes
• Performance
• Juggling Act
History
• Existing Rhino engine:
– Slow
– Non-compliant
– Did I mention slow?
• JavaScript since 1998:
– Adoption went through
the roof
– Technology advances
(V8, SpiderMonkey…)
Nashorn in a nutshell
• Project Nashorn
– Started in July 2011
– Integrates with JSR-
223
– Reference use-case
for JSR-292
• Released with Java 8
in March 2014
Why bother?
Why you care
• Extensibility and scripting
– Macro systems (a la VBA)
– Event hooks
• Server-side JavaScript
– More on this later
• End-user programmability
– Rule engines
– Reporting engines/ETL
– BPL and workflow
• … and more
Why Oracle cares
• Atwood’s law
• Node.js
– A real threat to Java’s
server-side growth
• Reference use-case for
JSR-292
– Drive innovation
– Drive optimization
– Reference implementation
Features
• Self-contained
• Implements ECMAScript 5.1
– 100% compliant!
• Runtime-compiled to bytecode
(no interpreted mode as with Rhino)
• Small: 1.5MB JAR
• Fast!
JSR-223 at a glance
import javax.script.*;
ScriptEngineManager manager =
new ScriptEngineManager();
ScriptEngine nashorn =
manager.getEngineByName("nashorn");
nashorn.eval(
"print("hello world!");");
Integrating JSR-223
• Injecting state
nashorn.put("name", "Schnitzel McFry");
nashorn.eval(
"print("hello " + name + "!");");
Integrating JSR-223
• Invoking JavaScript from Java
nashorn.eval(
"function hello(name) { " +
" print("hello " + name + "!");" +
"} " );
Invocable context = (Invocable) nashorn;
context.invokeFunction("hello", "world");
Nashorn Extensions
• Java object
– Java.type
– Java.extend
– Java.from
– Java.to
– Java.super
• A bunch more
Integrating JSR-223
• Invoking Java from JavaScript
nashorn.eval(
"var HashMap = Java.type("java.util.HashMap");" +
"var map = new HashMap(); " +
"map.put("name", "Schnitzel"); " +
"map.put("surname", "McFry"); " );
HashMap<String, String> map =
(HashMap<String, String>) nashorn.get("map");
Integrating JSR-223
• Implementing a Java interface
nashorn.eval(
"var runnable = { " +
" "run": function() { print("hello world"); }" +
"} " );
Invocable invocable = (Invocable) nashorn;
Runnable runnable = invocable.getInterface(
nashorn.get("runnable"), Runnable.class);
Integrating JSR-223
• Single Abstract Method (SAM)
promotion:
nashorn.eval(
"var Thread = Java.type("java.lang.Thread");" +
"var thread = new Thread(function() { " +
" print("hello world"); " +
"} ); " );
Thread thread = (Thread) nashorn.get("thread");
thread.start();
thread.join();
Behind the Scenes
The challenge
• JavaScript is dynamic
– Things can change at runtime
– Optimization is all about assumptions
The challenge
• JavaScript is dynamic
– Things can change at runtime
– Optimization is all about assumptions
• For example, what is the type of:
var x = 500000;
The challenge
• JavaScript is dynamic
– Things can change at runtime
– Optimization is all about assumptions
• For example, what is the type of:
var x = 500000;
x *= 500000; And now?
The challenge
• JavaScript is dynamic
– Things can change at runtime
– Optimization is all about assumptions
• For example, what is the type of:
var x = 500000;
x *= 500000; And now?
• How would you implement this?
The challenge
• Naïve multiplication operator:
– Receive LHS and RHS as Objects
– Unbox
– Test for potential over/underflow
– Add via appropriate codepath
– Box and return
• You can specialize via static analysis
• … but on-the-fly optimization is better
The challenge
• That’s just one
example.
– Dynamic dispatch
– Type coercions
– Primitive widening
– Prototype mutation
• All of these per call
site!
function square(x) {
return x * x;
}
square(10) //== 100
square(3.14) //== 9.8596
square("wat") //== NaN
The challenge
• Runtime code manipulation is not the
JVM’s strong suite
– Can only load entire classes
– High overhead
– Hard PermGen space limit
– Class unloading issues
Enter JSR 292
• 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!
invokedynamic
• The name is
misleading
• It’s not about
invocation
• … but about
runtime linkage
invokedynamic
Bootstrap
Method
Target
Call Site
Compile-time
Runtime
Invokes
Returns MethodHandle
java.lang.invoke
• MethodHandle
– An immutable
function pointer
– Composable:
• Guards
• Exception handlers
• Argument mutation
– Typesafe and
JIT-optimizable
• CallSite
– Optionally mutable
wrapper
– Binds an
invokedynamic
callsite to a target
MethodHandle
Why is this cool?
• Generated code is linked at runtime
• Code is hotswappable
– Guards for branching (over/underflow)
– SwitchPoints for hotswap (promotions)
• Hotswapping is lightweight
– No class generation or loading
• Resulting codepath can be JITted
Don’t forget JEP 122
• The PermGen space is no more
– Now called “Metaspace”
– Resides in native heap
– Block allocator and classloader isolation
– Dynamic size (with bounds)
• Maximum size (hard)
• Low/high watermark for GC
• This applies to all GCs (not just G1)
Dynalink
• An open-source library
• Builds on top of invokedynamic:
– Metaobject protocol
– Linkage model
• Enables cross-language interop
(JRuby, Jython, Nashorn, plain Java)
• Open source (Apache-licensed)
So how does it
perform?
Pretty damn good!
• 2-10 times faster than Rhino
• ~60% percent of V8
• Not much research out there
Avatar.js
• Implements the Node
model and API on the
JVM
• Supports most
modules
– Some natively
– Some via JNI
• … and it does work!
Supported module highlights
• mocha
• coffee-script
• uglify-js
• underscore
• request
• async
• jade
• express
• mongodb
• Redis
Most popular per nodejsmodules.org
QUESTIONS?
Thank you!
Thank you!
Additional reading:
• Nashorn war stories (from a
battle scarred veteran of
invokedynamic)
• Dynalink
Contact me:
• http://www.tomergabel.com
• tomer@tomergabel.com
• @tomerg

Mais conteúdo relacionado

Mais procurados

Node.js, toy or power tool?
Node.js, toy or power tool?Node.js, toy or power tool?
Node.js, toy or power tool?Ovidiu Dimulescu
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scalatakezoe
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Running JavaScript Efficiently in a Java World
Running JavaScript Efficiently in a Java WorldRunning JavaScript Efficiently in a Java World
Running JavaScript Efficiently in a Java Worldirbull
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architectureBen Lin
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Oscar Renalias
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaNurul Ferdous
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
KrakenJS
KrakenJSKrakenJS
KrakenJSPayPal
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 

Mais procurados (20)

Node.js, toy or power tool?
Node.js, toy or power tool?Node.js, toy or power tool?
Node.js, toy or power tool?
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Nashorn
NashornNashorn
Nashorn
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Running JavaScript Efficiently in a Java World
Running JavaScript Efficiently in a Java WorldRunning JavaScript Efficiently in a Java World
Running JavaScript Efficiently in a Java World
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architecture
 
The SPDY Protocol
The SPDY ProtocolThe SPDY Protocol
The SPDY Protocol
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, DhakaJavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
KrakenJS
KrakenJSKrakenJS
KrakenJS
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 

Semelhante a Nashorn: JavaScript that doesn’t suck (ILJUG)

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
 
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
 
JVM and Java Performance Tuning | JVM Tuning | Java Performance
JVM and Java Performance Tuning | JVM Tuning | Java PerformanceJVM and Java Performance Tuning | JVM Tuning | Java Performance
JVM and Java Performance Tuning | JVM Tuning | Java PerformanceAnand Narayanan
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]Miro Wengner
 
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
 
Lagergren jvmls-2014-final
Lagergren jvmls-2014-finalLagergren jvmls-2014-final
Lagergren jvmls-2014-finalMarcus Lagergren
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.jsKasey McCurdy
 
On-boarding with JanusGraph Performance
On-boarding with JanusGraph PerformanceOn-boarding with JanusGraph Performance
On-boarding with JanusGraph PerformanceChin Huang
 
DrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an AfterthoughtDrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an AfterthoughtNick Santamaria
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJSTim Sommer
 
Eureka Moment UKLUG
Eureka Moment UKLUGEureka Moment UKLUG
Eureka Moment UKLUGPaul Withers
 
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...InfinIT - Innovationsnetværket for it
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesAlexandra Masterson
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin Webber
 
Optimizing JavaScript and Dynamic Languages on the JVM
Optimizing JavaScript and Dynamic Languages on the JVMOptimizing JavaScript and Dynamic Languages on the JVM
Optimizing JavaScript and Dynamic Languages on the JVMMarcus Lagergren
 

Semelhante a Nashorn: JavaScript that doesn’t suck (ILJUG) (20)

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
 
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
 
JVM and Java Performance Tuning | JVM Tuning | Java Performance
JVM and Java Performance Tuning | JVM Tuning | Java PerformanceJVM and Java Performance Tuning | JVM Tuning | Java Performance
JVM and Java Performance Tuning | JVM Tuning | Java Performance
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
 
Lagergren jvmls-2014-final
Lagergren jvmls-2014-finalLagergren jvmls-2014-final
Lagergren jvmls-2014-final
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
 
On-boarding with JanusGraph Performance
On-boarding with JanusGraph PerformanceOn-boarding with JanusGraph Performance
On-boarding with JanusGraph Performance
 
DrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an AfterthoughtDrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an Afterthought
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
 
Eureka Moment UKLUG
Eureka Moment UKLUGEureka Moment UKLUG
Eureka Moment UKLUG
 
Ruby on the JVM
Ruby on the JVMRuby on the JVM
Ruby on the JVM
 
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
 
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...Towards "write once - run whenever possible" with Safety Critical Java af Ben...
Towards "write once - run whenever possible" with Safety Critical Java af Ben...
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Kaggle nlp approaches
Kaggle nlp approachesKaggle nlp approaches
Kaggle nlp approaches
 
Optimizing JavaScript and Dynamic Languages on the JVM
Optimizing JavaScript and Dynamic Languages on the JVMOptimizing JavaScript and Dynamic Languages on the JVM
Optimizing JavaScript and Dynamic Languages on the JVM
 

Mais de Tomer Gabel

How shit works: Time
How shit works: TimeHow shit works: Time
How shit works: TimeTomer Gabel
 
Nondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsNondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsTomer Gabel
 
Slaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency InjectionSlaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency InjectionTomer Gabel
 
An Abridged Guide to Event Sourcing
An Abridged Guide to Event SourcingAn Abridged Guide to Event Sourcing
An Abridged Guide to Event SourcingTomer Gabel
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPUTomer Gabel
 
How Shit Works: Storage
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: StorageTomer Gabel
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryTomer Gabel
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice StackTomer Gabel
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitTomer Gabel
 
Onboarding at Scale
Onboarding at ScaleOnboarding at Scale
Onboarding at ScaleTomer Gabel
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the WildTomer Gabel
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Tomer Gabel
 
Put Your Thinking CAP On
Put Your Thinking CAP OnPut Your Thinking CAP On
Put Your Thinking CAP OnTomer Gabel
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationTomer Gabel
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaTomer Gabel
 
Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)Tomer Gabel
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala AdoptionTomer Gabel
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With ScalaTomer Gabel
 

Mais de Tomer Gabel (20)

How shit works: Time
How shit works: TimeHow shit works: Time
How shit works: Time
 
Nondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsNondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of Us
 
Slaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency InjectionSlaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency Injection
 
An Abridged Guide to Event Sourcing
An Abridged Guide to Event SourcingAn Abridged Guide to Event Sourcing
An Abridged Guide to Event Sourcing
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
 
How Shit Works: Storage
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: Storage
 
Java 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala Story
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Onboarding at Scale
Onboarding at ScaleOnboarding at Scale
Onboarding at Scale
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)
 
Put Your Thinking CAP On
Put Your Thinking CAP OnPut Your Thinking CAP On
Put Your Thinking CAP On
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
 
A Field Guide to DSL Design in Scala
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
 
Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)Functional Leap of Faith (Keynote at JDay Lviv 2014)
Functional Leap of Faith (Keynote at JDay Lviv 2014)
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 

Último

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Último (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Nashorn: JavaScript that doesn’t suck (ILJUG)

  • 1. Nashorn: JavaScript that doesn’t suck Tomer Gabel, Wix ILJUG, April 2014
  • 2. Agenda • History • Features • Behind the scenes • Performance • Juggling Act
  • 3. History • Existing Rhino engine: – Slow – Non-compliant – Did I mention slow? • JavaScript since 1998: – Adoption went through the roof – Technology advances (V8, SpiderMonkey…)
  • 4. Nashorn in a nutshell • Project Nashorn – Started in July 2011 – Integrates with JSR- 223 – Reference use-case for JSR-292 • Released with Java 8 in March 2014
  • 5. Why bother? Why you care • Extensibility and scripting – Macro systems (a la VBA) – Event hooks • Server-side JavaScript – More on this later • End-user programmability – Rule engines – Reporting engines/ETL – BPL and workflow • … and more Why Oracle cares • Atwood’s law • Node.js – A real threat to Java’s server-side growth • Reference use-case for JSR-292 – Drive innovation – Drive optimization – Reference implementation
  • 6. Features • Self-contained • Implements ECMAScript 5.1 – 100% compliant! • Runtime-compiled to bytecode (no interpreted mode as with Rhino) • Small: 1.5MB JAR • Fast!
  • 7. JSR-223 at a glance import javax.script.*; ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine nashorn = manager.getEngineByName("nashorn"); nashorn.eval( "print("hello world!");");
  • 8. Integrating JSR-223 • Injecting state nashorn.put("name", "Schnitzel McFry"); nashorn.eval( "print("hello " + name + "!");");
  • 9. Integrating JSR-223 • Invoking JavaScript from Java nashorn.eval( "function hello(name) { " + " print("hello " + name + "!");" + "} " ); Invocable context = (Invocable) nashorn; context.invokeFunction("hello", "world");
  • 10. Nashorn Extensions • Java object – Java.type – Java.extend – Java.from – Java.to – Java.super • A bunch more
  • 11. Integrating JSR-223 • Invoking Java from JavaScript nashorn.eval( "var HashMap = Java.type("java.util.HashMap");" + "var map = new HashMap(); " + "map.put("name", "Schnitzel"); " + "map.put("surname", "McFry"); " ); HashMap<String, String> map = (HashMap<String, String>) nashorn.get("map");
  • 12. Integrating JSR-223 • Implementing a Java interface nashorn.eval( "var runnable = { " + " "run": function() { print("hello world"); }" + "} " ); Invocable invocable = (Invocable) nashorn; Runnable runnable = invocable.getInterface( nashorn.get("runnable"), Runnable.class);
  • 13. Integrating JSR-223 • Single Abstract Method (SAM) promotion: nashorn.eval( "var Thread = Java.type("java.lang.Thread");" + "var thread = new Thread(function() { " + " print("hello world"); " + "} ); " ); Thread thread = (Thread) nashorn.get("thread"); thread.start(); thread.join();
  • 15. The challenge • JavaScript is dynamic – Things can change at runtime – Optimization is all about assumptions
  • 16. The challenge • JavaScript is dynamic – Things can change at runtime – Optimization is all about assumptions • For example, what is the type of: var x = 500000;
  • 17. The challenge • JavaScript is dynamic – Things can change at runtime – Optimization is all about assumptions • For example, what is the type of: var x = 500000; x *= 500000; And now?
  • 18. The challenge • JavaScript is dynamic – Things can change at runtime – Optimization is all about assumptions • For example, what is the type of: var x = 500000; x *= 500000; And now? • How would you implement this?
  • 19. The challenge • Naïve multiplication operator: – Receive LHS and RHS as Objects – Unbox – Test for potential over/underflow – Add via appropriate codepath – Box and return • You can specialize via static analysis • … but on-the-fly optimization is better
  • 20. The challenge • That’s just one example. – Dynamic dispatch – Type coercions – Primitive widening – Prototype mutation • All of these per call site! function square(x) { return x * x; } square(10) //== 100 square(3.14) //== 9.8596 square("wat") //== NaN
  • 21. The challenge • Runtime code manipulation is not the JVM’s strong suite – Can only load entire classes – High overhead – Hard PermGen space limit – Class unloading issues
  • 22. Enter JSR 292 • 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!
  • 23. invokedynamic • The name is misleading • It’s not about invocation • … but about runtime linkage invokedynamic Bootstrap Method Target Call Site Compile-time Runtime Invokes Returns MethodHandle
  • 24. java.lang.invoke • MethodHandle – An immutable function pointer – Composable: • Guards • Exception handlers • Argument mutation – Typesafe and JIT-optimizable • CallSite – Optionally mutable wrapper – Binds an invokedynamic callsite to a target MethodHandle
  • 25. Why is this cool? • Generated code is linked at runtime • Code is hotswappable – Guards for branching (over/underflow) – SwitchPoints for hotswap (promotions) • Hotswapping is lightweight – No class generation or loading • Resulting codepath can be JITted
  • 26. Don’t forget JEP 122 • The PermGen space is no more – Now called “Metaspace” – Resides in native heap – Block allocator and classloader isolation – Dynamic size (with bounds) • Maximum size (hard) • Low/high watermark for GC • This applies to all GCs (not just G1)
  • 27. Dynalink • An open-source library • Builds on top of invokedynamic: – Metaobject protocol – Linkage model • Enables cross-language interop (JRuby, Jython, Nashorn, plain Java) • Open source (Apache-licensed)
  • 28. So how does it perform?
  • 29. Pretty damn good! • 2-10 times faster than Rhino • ~60% percent of V8 • Not much research out there
  • 30. Avatar.js • Implements the Node model and API on the JVM • Supports most modules – Some natively – Some via JNI • … and it does work! Supported module highlights • mocha • coffee-script • uglify-js • underscore • request • async • jade • express • mongodb • Redis Most popular per nodejsmodules.org
  • 32. Thank you! Additional reading: • Nashorn war stories (from a battle scarred veteran of invokedynamic) • Dynalink Contact me: • http://www.tomergabel.com • tomer@tomergabel.com • @tomerg