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

More Related Content

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?
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
 
Nashorn
NashornNashorn
Nashorn
Rory Preddy
 
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
takezoe
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Arun Kumar Arjunan
 
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
Ganesh 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.js
Gary Yeh
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
jacekbecela
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
David 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 World
irbull
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architecture
Ben Lin
 
The SPDY Protocol
The SPDY ProtocolThe SPDY Protocol
The SPDY Protocol
Fabian Lange
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
Oscar Renalias
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
JITENDRA 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, Dhaka
Nurul Ferdous
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
KrakenJS
KrakenJSKrakenJS
KrakenJS
PayPal
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Dinesh U
 
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 Scala
takezoe
 
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
Ganesh 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.js
Gary Yeh
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
jacekbecela
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
David 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 World
irbull
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architecture
Ben Lin
 
Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
Oscar Renalias
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
JITENDRA 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, Dhaka
Nurul Ferdous
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
KrakenJS
KrakenJSKrakenJS
KrakenJS
PayPal
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Dinesh U
 

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
Codemotion 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 Roma
Vitalij 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 Performance
Anand Narayanan
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
CodeFest
 
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-final
Marcus Lagergren
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
Kasey McCurdy
 
On-boarding with JanusGraph Performance
On-boarding with JanusGraph PerformanceOn-boarding with JanusGraph Performance
On-boarding with JanusGraph Performance
Chin Huang
 
DrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an AfterthoughtDrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an Afterthought
Nick Santamaria
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
Tim Sommer
 
Eureka Moment UKLUG
Eureka Moment UKLUGEureka Moment UKLUG
Eureka Moment UKLUG
Paul Withers
 
Ruby on the JVM
Ruby on the JVMRuby on the JVM
Ruby on the JVM
Kresten Krab Thorup
 
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
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
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 Slides
Alexandra Masterson
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
Kevin Webber
 
JS Essence
JS EssenceJS Essence
JS Essence
Uladzimir Piatryka
 
Kaggle nlp approaches
Kaggle nlp approachesKaggle nlp approaches
Kaggle nlp approaches
prabu palanisamy
 
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
Marcus Lagergren
 
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
Codemotion 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 Roma
Vitalij 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 Performance
Anand Narayanan
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
CodeFest
 
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-final
Marcus Lagergren
 
An introduction to Node.js
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
Kasey McCurdy
 
On-boarding with JanusGraph Performance
On-boarding with JanusGraph PerformanceOn-boarding with JanusGraph Performance
On-boarding with JanusGraph Performance
Chin Huang
 
DrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an AfterthoughtDrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an Afterthought
Nick Santamaria
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
Tim Sommer
 
Eureka Moment UKLUG
Eureka Moment UKLUGEureka Moment UKLUG
Eureka Moment UKLUG
Paul 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 Slides
Alexandra Masterson
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
Kevin 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 JVM
Marcus Lagergren
 
Ad

More from Tomer Gabel (20)

How shit works: Time
How shit works: TimeHow shit works: Time
How shit works: Time
Tomer 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 Us
Tomer Gabel
 
Slaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency InjectionSlaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency Injection
Tomer Gabel
 
An Abridged Guide to Event Sourcing
An Abridged Guide to Event SourcingAn Abridged Guide to Event Sourcing
An Abridged Guide to Event Sourcing
Tomer Gabel
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
Tomer Gabel
 
How Shit Works: Storage
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: Storage
Tomer 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 Story
Tomer Gabel
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
Tomer 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 Profit
Tomer Gabel
 
Onboarding at Scale
Onboarding at ScaleOnboarding at Scale
Onboarding at Scale
Tomer Gabel
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
Tomer 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 On
Tomer Gabel
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
Tomer 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 Scala
Tomer 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 Classes
Tomer Gabel
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
Tomer Gabel
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
How shit works: Time
How shit works: TimeHow shit works: Time
How shit works: Time
Tomer 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 Us
Tomer Gabel
 
Slaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency InjectionSlaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency Injection
Tomer Gabel
 
An Abridged Guide to Event Sourcing
An Abridged Guide to Event SourcingAn Abridged Guide to Event Sourcing
An Abridged Guide to Event Sourcing
Tomer Gabel
 
How shit works: the CPU
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
Tomer Gabel
 
How Shit Works: Storage
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: Storage
Tomer 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 Story
Tomer Gabel
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
Tomer 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 Profit
Tomer Gabel
 
Onboarding at Scale
Onboarding at ScaleOnboarding at Scale
Onboarding at Scale
Tomer Gabel
 
Scala in the Wild
Scala in the WildScala in the Wild
Scala in the Wild
Tomer 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 On
Tomer Gabel
 
Leveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
Tomer 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 Scala
Tomer 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 Classes
Tomer Gabel
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
Tomer Gabel
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel
 
Ad

Recently uploaded (20)

Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 

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 • [email protected] • @tomerg