SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Recently uploaded (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
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...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

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