Nashorn: JavaScript that doesn’t suck (ILJUG)

Tomer Gabel
Tomer GabelConsulting Engineer at Substrate Software Services
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
1 of 32

Recommended

Nashorn by
NashornNashorn
NashornEverett Toews
1.7K views32 slides
Server-Side JavaScript with Nashorn by
Server-Side JavaScript with NashornServer-Side JavaScript with Nashorn
Server-Side JavaScript with NashornDaniel Woods
2.5K views19 slides
Lagergren jvmls-2013-final by
Lagergren jvmls-2013-finalLagergren jvmls-2013-final
Lagergren jvmls-2013-finalMarcus Lagergren
4.3K views108 slides
Javantura 2014 - Java 8 JavaScript Nashorn by
Javantura 2014 - Java 8 JavaScript NashornJavantura 2014 - Java 8 JavaScript Nashorn
Javantura 2014 - Java 8 JavaScript NashornMiroslav Resetar
2K views22 slides
Java/Spring과 Node.js의 공존 시즌2 by
Java/Spring과 Node.js의 공존 시즌2Java/Spring과 Node.js의 공존 시즌2
Java/Spring과 Node.js의 공존 시즌2동수 장
9.5K views54 slides
Understanding the Single Thread Event Loop by
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event LoopTorontoNodeJS
1.8K views18 slides

More Related Content

What's hot

Node.js, toy or power tool? by
Node.js, toy or power tool?Node.js, toy or power tool?
Node.js, toy or power tool?Ovidiu Dimulescu
4.9K views37 slides
Introduction to Node.js: What, why and how? by
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
1.6K views21 slides
Nashorn by
NashornNashorn
NashornRory Preddy
441 views33 slides
GitBucket: The perfect Github clone by Scala by
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scalatakezoe
26.7K views37 slides
Introduction to node.js by
Introduction to node.jsIntroduction to node.js
Introduction to node.jsArun Kumar Arjunan
3K views55 slides
Nodejs Event Driven Concurrency for Web Applications by
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
7.4K views83 slides

What's hot(20)

Introduction to Node.js: What, why and how? by Christian Joudrey
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 Joudrey1.6K views
GitBucket: The perfect Github clone by Scala by takezoe
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
takezoe26.7K views
Nodejs Event Driven Concurrency for Web Applications by Ganesh Iyer
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer7.4K views
Basic Understanding and Implement of Node.js by Gary Yeh
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
Gary Yeh886 views
Introduction to Node.js by Rob O'Doherty
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Rob O'Doherty2.9K views
Introduction to node.js by jacekbecela
Introduction to node.jsIntroduction to node.js
Introduction to node.js
jacekbecela9.4K views
Introduction to Node.js by Vikash Singh
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh71.2K views
All aboard the NodeJS Express by David Boyer
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
David Boyer11.3K views
Running JavaScript Efficiently in a Java World by irbull
Running JavaScript Efficiently in a Java WorldRunning JavaScript Efficiently in a Java World
Running JavaScript Efficiently in a Java World
irbull9.8K views
Webconf nodejs-production-architecture by Ben Lin
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architecture
Ben Lin8.9K views
The SPDY Protocol by Fabian Lange
The SPDY ProtocolThe SPDY Protocol
The SPDY Protocol
Fabian Lange13.4K views
Node.js, for architects - OpenSlava 2013 by Oscar Renalias
Node.js, for architects - OpenSlava 2013Node.js, for architects - OpenSlava 2013
Node.js, for architects - OpenSlava 2013
Oscar Renalias13.7K views
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka by Nurul Ferdous
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 Ferdous2.5K views
Java script at backend nodejs by Amit Thakkar
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar1.8K views
KrakenJS by PayPal
KrakenJSKrakenJS
KrakenJS
PayPal6.6K views
Introduction to node.js by Dinesh U
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Dinesh U640 views

Similar to Nashorn: JavaScript that doesn’t suck (ILJUG)

Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix by
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
1K views30 slides
Java 8: Nashorn & avatar.js di Enrico Risa al JUG Roma by
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
3K views42 slides
JVM and Java Performance Tuning | JVM Tuning | Java Performance by
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
641 views12 slides
Raffaele Rialdi by
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
207 views19 slides
New Java features: Simplified Design Patterns[LIT3826] by
New Java features: Simplified Design Patterns[LIT3826]New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]Miro Wengner
39 views22 slides
Java script nirvana in netbeans [con5679] by
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Ryan Cuprak
1.1K views76 slides

Similar to Nashorn: JavaScript that doesn’t suck (ILJUG)(20)

Nashorn: JavaScript that doesn't suck - Tomer Gabel, Wix by Codemotion Tel Aviv
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
JVM and Java Performance Tuning | JVM Tuning | Java Performance by Anand Narayanan
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 Narayanan641 views
Raffaele Rialdi by CodeFest
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
CodeFest207 views
New Java features: Simplified Design Patterns[LIT3826] by Miro Wengner
New Java features: Simplified Design Patterns[LIT3826]New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]
Miro Wengner39 views
Java script nirvana in netbeans [con5679] by Ryan Cuprak
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
Ryan Cuprak1.1K views
An introduction to Node.js by Kasey McCurdy
An introduction to Node.jsAn introduction to Node.js
An introduction to Node.js
Kasey McCurdy788 views
On-boarding with JanusGraph Performance by Chin Huang
On-boarding with JanusGraph PerformanceOn-boarding with JanusGraph Performance
On-boarding with JanusGraph Performance
Chin Huang7.7K views
DrupalSouth 2015 - Performance: Not an Afterthought by Nick Santamaria
DrupalSouth 2015 - Performance: Not an AfterthoughtDrupalSouth 2015 - Performance: Not an Afterthought
DrupalSouth 2015 - Performance: Not an Afterthought
Nick Santamaria377 views
T4T Training day - NodeJS by Tim Sommer
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
Tim Sommer764 views
Play Framework and Activator by Kevin Webber
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
Kevin Webber4.1K views
Optimizing JavaScript and Dynamic Languages on the JVM by Marcus Lagergren
Optimizing JavaScript and Dynamic Languages on the JVMOptimizing JavaScript and Dynamic Languages on the JVM
Optimizing JavaScript and Dynamic Languages on the JVM
Marcus Lagergren2.1K views

More from Tomer Gabel

How shit works: Time by
How shit works: TimeHow shit works: Time
How shit works: TimeTomer Gabel
342 views53 slides
Nondeterministic Software for the Rest of Us by
Nondeterministic Software for the Rest of UsNondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of UsTomer Gabel
329 views39 slides
Slaying Sacred Cows: Deconstructing Dependency Injection by
Slaying Sacred Cows: Deconstructing Dependency InjectionSlaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency InjectionTomer Gabel
1.3K views34 slides
An Abridged Guide to Event Sourcing by
An Abridged Guide to Event SourcingAn Abridged Guide to Event Sourcing
An Abridged Guide to Event SourcingTomer Gabel
1K views32 slides
How shit works: the CPU by
How shit works: the CPUHow shit works: the CPU
How shit works: the CPUTomer Gabel
1.8K views38 slides
How Shit Works: Storage by
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: StorageTomer Gabel
914 views44 slides

More from Tomer Gabel(20)

How shit works: Time by Tomer Gabel
How shit works: TimeHow shit works: Time
How shit works: Time
Tomer Gabel342 views
Nondeterministic Software for the Rest of Us by Tomer Gabel
Nondeterministic Software for the Rest of UsNondeterministic Software for the Rest of Us
Nondeterministic Software for the Rest of Us
Tomer Gabel329 views
Slaying Sacred Cows: Deconstructing Dependency Injection by Tomer Gabel
Slaying Sacred Cows: Deconstructing Dependency InjectionSlaying Sacred Cows: Deconstructing Dependency Injection
Slaying Sacred Cows: Deconstructing Dependency Injection
Tomer Gabel1.3K views
An Abridged Guide to Event Sourcing by Tomer Gabel
An Abridged Guide to Event SourcingAn Abridged Guide to Event Sourcing
An Abridged Guide to Event Sourcing
Tomer Gabel1K views
How shit works: the CPU by Tomer Gabel
How shit works: the CPUHow shit works: the CPU
How shit works: the CPU
Tomer Gabel1.8K views
How Shit Works: Storage by Tomer Gabel
How Shit Works: StorageHow Shit Works: Storage
How Shit Works: Storage
Tomer Gabel914 views
Java 8 and Beyond, a Scala Story by Tomer Gabel
Java 8 and Beyond, a Scala StoryJava 8 and Beyond, a Scala Story
Java 8 and Beyond, a Scala Story
Tomer Gabel747 views
The Wix Microservice Stack by Tomer Gabel
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
Tomer Gabel1.7K views
Scala Refactoring for Fun and Profit (Japanese subtitles) by 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)
Tomer Gabel6.6K views
Scala Refactoring for Fun and Profit by Tomer Gabel
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
Tomer Gabel985 views
Onboarding at Scale by Tomer Gabel
Onboarding at ScaleOnboarding at Scale
Onboarding at Scale
Tomer Gabel1.5K views
Scala in the Wild by Tomer Gabel
Scala in the WildScala in the Wild
Scala in the Wild
Tomer Gabel2.8K views
Speaking Scala: Refactoring for Fun and Profit (Workshop) by 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)
Tomer Gabel765 views
Put Your Thinking CAP On by Tomer Gabel
Put Your Thinking CAP OnPut Your Thinking CAP On
Put Your Thinking CAP On
Tomer Gabel3.5K views
Leveraging Scala Macros for Better Validation by Tomer Gabel
Leveraging Scala Macros for Better ValidationLeveraging Scala Macros for Better Validation
Leveraging Scala Macros for Better Validation
Tomer Gabel1.4K views
A Field Guide to DSL Design in Scala by Tomer Gabel
A Field Guide to DSL Design in ScalaA Field Guide to DSL Design in Scala
A Field Guide to DSL Design in Scala
Tomer Gabel6.5K views
Functional Leap of Faith (Keynote at JDay Lviv 2014) by 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)
Tomer Gabel1.5K views
Scala Back to Basics: Type Classes by Tomer Gabel
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel3.7K views
5 Bullets to Scala Adoption by Tomer Gabel
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
Tomer Gabel2.7K views
Ponies and Unicorns With Scala by Tomer Gabel
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
Tomer Gabel961 views

Recently uploaded

ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...Jasper Oosterveld
19 views49 slides
Mini-Track: AI and ML in Network Operations Applications by
Mini-Track: AI and ML in Network Operations ApplicationsMini-Track: AI and ML in Network Operations Applications
Mini-Track: AI and ML in Network Operations ApplicationsNetwork Automation Forum
10 views24 slides
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...James Anderson
92 views32 slides
Powerful Google developer tools for immediate impact! (2023-24) by
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)wesley chun
10 views38 slides
Voice Logger - Telephony Integration Solution at Aegis by
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at AegisNirmal Sharma
39 views1 slide
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensorssugiuralab
21 views15 slides

Recently uploaded(20)

ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ... by Jasper Oosterveld
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
ESPC 2023 - Protect and Govern your Sensitive Data with Microsoft Purview in ...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson92 views
Powerful Google developer tools for immediate impact! (2023-24) by wesley chun
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)
wesley chun10 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma39 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab21 views
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f... by TrustArc
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc Webinar - Managing Online Tracking Technology Vendors_ A Checklist f...
TrustArc11 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi132 views
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
Future of AR - Facebook Presentation by ssuserb54b561
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
ssuserb54b56115 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn22 views
Data Integrity for Banking and Financial Services by Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely25 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院

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