JavaOne 2014: Java vs JavaScript
-
Upload
chris-bailey -
Category
Software
-
view
602 -
download
2
description
Transcript of JavaOne 2014: Java vs JavaScript
© 2014 IBM Corporation
Chris Bailey – IBM Runtime Monitoring and Diagnostics
1st October 2014
Java vs JavaScriptHead to Head
Document number
© 2014 IBM Corporation
Important Disclaimers
THE INFORMATION CONTAINED IN THIS PRESENTATION IS PROVIDED FOR INFORMATIONAL PURPOSES ONLY.
WHILST EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND ACCURACY OF THE INFORMATION CONTAINED IN THIS PRESENTATION, IT IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
ALL PERFORMANCE DATA INCLUDED IN THIS PRESENTATION HAVE BEEN GATHERED IN A CONTROLLED ENVIRONMENT. YOUR OWN TEST RESULTS MAY VARY BASED ON HARDWARE, SOFTWARE OR INFRASTRUCTURE DIFFERENCES.
ALL DATA INCLUDED IN THIS PRESENTATION ARE MEANT TO BE USED ONLY AS A GUIDE.
IN ADDITION, THE INFORMATION CONTAINED IN THIS PRESENTATION IS BASED ON IBM’S CURRENT PRODUCT PLANS AND STRATEGY, WHICH ARE SUBJECT TO CHANGE BY IBM, WITHOUT NOTICE.
IBM AND ITS AFFILIATED COMPANIES SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT OF THE USE OF, OR OTHERWISE RELATED TO, THIS PRESENTATION OR ANY OTHER DOCUMENTATION.
NOTHING CONTAINED IN THIS PRESENTATION IS INTENDED TO, OR SHALL HAVE THE EFFECT OF:
- CREATING ANY WARRANT OR REPRESENTATION FROM IBM, ITS AFFILIATED COMPANIES OR ITS OR THEIR SUPPLIERS AND/OR LICENSORS
2
© 2014 IBM Corporation3
A Quick Survey
© 2014 IBM Corporation4
What languages do you program in?
Java JavaScript Both0
10
20
30
40
50
60
Pe
rce
nta
ge
of A
ud
ien
ce
© 2014 IBM Corporation5
What runtimes do you use?
Server Java Applets JS in Browser Node.js Rhino Nashorn Avatar.js0
10
20
30
40
50
60
70
80
90
100
Pe
rce
nta
ge
of A
ud
ien
ce
© 2014 IBM Corporation6
Introduction to the speaker Chris Bailey
IBM Runtime Monitoring and Diagnostics Architect- 14 years working with Java and JVM technologies- 6 months working with Node.js and V8
Recent work focus:- Java monitoring, diagnostics and troubleshooting- Java integration into the cloud- JavaScript monitoring, diagnostics and troubleshooting
My contact information:- [email protected] http://www.linkedin.com/in/chrisbaileyibm- http://www.slideshare.net/cnbailey/- @Chris__Bailey
© 2014 IBM Corporation7
Goals of this talk
● Langage Adoption
● Deployment Modes
● Introduction to Node.js
● Asynchronous IO
● WebApplication Performance
● Under the Hood of Node.js
● JavaScript on the JVM
© 2014 IBM Corporation8
Language Adoption
© 2014 IBM Corporation9
GitHub Adoption: Java
© 2014 IBM Corporation10
GitHub Adoption: JavaScript
GitHut Adoption
© 2014 IBM Corporation11
Modulecounts.com
© 2014 IBM Corporation12
StackOverFlow Survey
© 2014 IBM Corporation13
Tiobe Programming Community Index
● Ratings based on the number of skilled engineers, courses and third party vendors.
© 2014 IBM Corporation14
Indeed.com Job Trends
© 2014 IBM Corporation15
Indeed.com Job Trends
© 2014 IBM Corporation16
Language Adoption JavaScript has a large developer base
- #1 on GitHub with 48.8% more active repositories than Java- #1 on modulecounts.com with 10% more NPM modules than Maven - #1 used language by StackOverflow survey responders- #9 language on the Tiobe index
Java remains a hugely relevant language, particularly on the server - #2 on GitHub with xx% more than the next language- #3 on modulecounts.com with 73.8% more modules than the next language- #2 language on the Tiobe index- #1 on indeed.com for developer jobs
© 2014 IBM Corporation17
Deployment Modes
© 2014 IBM Corporation18
Usage in the Browser● JavaScript is ubiquitous in the browser
- Supported in every browser- Full integration with HTML and CSS
● Not affected by negative publicity....
Unless it is absolutely necessary to run Java in web browsers, disable it as describedbelow, even after updating to 7u11. This will help mitigate other Java vulnerabilities thatmay be discovered in the future.
This and previous Java vulnerabilities have been widely targeted by attackers, and new Java vulnerabilities are likely to be discovered. To defend against this and future Java vulnerabilities, consider disabling Java in web browsers…
© 2014 IBM Corporation19
Usage on the Server● Java has a long history on the server
- JPE launched in 1998
● Java has rich platform support:- Linux x86, Linux POWER, zLinux- Windows, Mac OS, Solaris, AIX, z/OS
JavaScript is a nascent language on the server- Limited platform support – although its growing- No API support to interact with the OS
Part of the browser security model- Frameworks like Node.js have changed that.
© 2014 IBM Corporation20
Introduction to Node.js Single Threaded Event based JavaScript framework
– Uses non-blocking asynchronous I/O
Wraps the Chrome V8 JavaScript engine with I/O interfaces– Libuv provides interaction with OS/system
● Designed to build scalable network applications– Suited for real time delivery of data to distributed client
Available on a growing set of platforms- Windows, Linux x86, Linux ARM, Mac OS, Solaris- Linux POWER, zLinux, AIX
libuvV8
Node Bindings
Node Standard Library
C
JavaScript
© 2014 IBM Corporation21
Async I/O Model
© 2014 IBM Corporation22
Typical approach to IO One thread (or process) per connection
- Each thread waits on a response- Scalability determined by the number of threads
Each thread:- consumes memory- is relatively idle
Number of concurrent customers determined by number of depot workers
Additional customers wait in a queue with no response
© 2014 IBM Corporation23
Asynchronous non-blocking IO One thread multiplexes for multiple requests
- No waiting for a response- Handles return from I/O when notified
Scalability determined by:- CPU usage- “Back end” responsiveness
Number of concurrent customers determined by how fast the food Server can work
Or until the kitchen gets slammed
© 2014 IBM Corporation24
Drawbacks of Asynchronous IO Tasks must execute quickly to avoid blocking the event queue
- Analogous to work done under a lock- Stick to the right jobs, eg, I/O- Delegate CPU bound tasks to back end processes
Easy to run out of memory- No direct bound on amount of parallel work- Holding state for each piece or work means unbounded memory usage
© 2014 IBM Corporation25
JavaScript and Asynchronous IO JavaScript is already event based in the browser
- eg. onClick and onMouseOver events
First class functions and closures fit well with events- Easy to create and pass function callbacks- Easy to execute callbacks in the context of the event
Node.js execution is based on an event loop- Asynchronous I/O built in from the ground up
Node.js execution uses a single thread- No need to worry about locking or shared data- Most machines are now multi-CPU, so cluster capabilities are provided
© 2014 IBM Corporation26
HTTP Server Examplevar cluster = require('cluster');var cpus = require('os').cpus().length;var http = require('http');
if (cluster.isMaster) { for (var i = 0; i < cpus; i++) { cluster.fork(); } cluster.on('death', function(worker) { console.log("Worker" + worker.pid + "died"); });} else {
http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World!\n"); response.end();
}).listen(8080);}
© 2014 IBM Corporation27
HTTP Server Example with Clusteringvar cluster = require('cluster');var cpus = require('os').cpus().length;var http = require('http');
if (cluster.isMaster) { for (var i = 0; i < cpus; i++) { cluster.fork(); } cluster.on('death', function(worker) { console.log("Worker" + worker.pid + "died"); });} else {
http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World!\n"); response.end();
}).listen(8080);}
© 2014 IBM Corporation28
Event Loop Example Hypothetical implementation of readFile():
function readFile(filename, cb) { nb_open(filename, function(err, fd) { if (err) cb(err, null); nb_read(fd, function(err, data) { cb(err, data); nb_close(fd); }); });}
© 2014 IBM Corporation29
© 2014 IBM Corporation30
© 2014 IBM Corporation31
© 2014 IBM Corporation32
© 2014 IBM Corporation33
© 2014 IBM Corporation34
© 2014 IBM Corporation35
© 2014 IBM Corporation36
© 2014 IBM Corporation37
© 2014 IBM Corporation38
© 2014 IBM Corporation39
© 2014 IBM Corporation40
© 2014 IBM Corporation41
© 2014 IBM Corporation42
© 2014 IBM Corporation43
© 2014 IBM Corporation44
© 2014 IBM Corporation45
© 2014 IBM Corporation46
© 2014 IBM Corporation47
© 2014 IBM Corporation48
© 2014 IBM Corporation49
© 2014 IBM Corporation50
© 2014 IBM Corporation51
© 2014 IBM Corporation52
© 2014 IBM Corporation53
© 2014 IBM Corporation54
© 2014 IBM Corporation55
© 2014 IBM Corporation56
© 2014 IBM Corporation57
© 2014 IBM Corporation58
© 2014 IBM Corporation59
© 2014 IBM Corporation60
© 2014 IBM Corporation61
© 2014 IBM Corporation62
© 2014 IBM Corporation63
© 2014 IBM Corporation64
JavaScript and Asynchronous I/O Very little time spent with events on the Event Loop
Provides good scalability, so should provide great performance for IO bound apps
Like WebApplications...
© 2014 IBM Corporation65
WebApp Performance
© 2014 IBM Corporation66
JSON Serialization JSON serialization of a newly
instantiated object
Maps- Key of message- Value of Hello, World!
Example response:
Results from TechEmpower.com Round 9 tests (2014-05-01)
© 2014 IBM Corporation67
JSON Serialization JSON serialization of a newly
instantiated object
Maps- Key of message- Value of Hello, World!
Example response:
Results from TechEmpower.com Round 9 tests (2014-05-01)
© 2014 IBM Corporation68
Single Query Fetches single row from simple
database table
Row serialized as JSON
Example response:
Results from TechEmpower.com Round 9 tests (2014-05-01)
© 2014 IBM Corporation69
Single Query Fetches single row from simple
database table
Row serialized as JSON
Example response:
Results from TechEmpower.com Round 9 tests (2014-05-01)
© 2014 IBM Corporation70
Multiple Query Fetches multiple rows from a
simple database table
Rows serialized as JSON
Example response:
Results from TechEmpower.com Round 9 tests (2014-05-01)
© 2014 IBM Corporation71
Multiple Query Fetches multiple rows from a
simple database table
Rows serialized as JSON
Example response:
Results from TechEmpower.com Round 9 tests (2014-05-01)
© 2014 IBM Corporation72
Data Updates Fetches multiple rows from a
simple database table
Converts rows to objects and modifies one attribute of each object
Updates each associated row and serializes as JSON
Example Response:
Results taken from TechEmpower.com
© 2014 IBM Corporation73
Data Updates Fetches multiple rows from a
simple database table
Converts rows to objects and modifies one attribute of each object
Updates each associated row and serializes as JSON
Example Response:
Results taken from TechEmpower.com
© 2014 IBM Corporation74
Under the Hood
© 2014 IBM Corporation75
Polymorphism and Object Representation
Class pointer
Locks
Flags
int
Class pointer
Locks
Flags
int
Class pointer
Locks
Flags
int
Class pointer
Locks
Flags
int
Integer Object Name: Integer
Method Table
Super Class
Field Table
Constant Pool
Object Offsets
...
Integer Class
Java objects are fixed in size and shape- Determined by the object type- Type determined by class pointer
Class pointer gives access to Method Table- All methods executable from the object
Class pointer also gives access to Object Offsets- Fields in the object that are objects- Used for graph traversal during GC
© 2014 IBM Corporation76
Polymorphism and Object Representation
Field: offset
Field: offset
Field: offset
Map
1:
Length
2:
JSObject
JavaScript objects polymorphic and can change in size and shape
“Simple” objects:- Created with 32 fields- Contains a Map describing key : value
parings- Contains “extra properties” for overflow- Contains “elements” for array values- All fields are 64bits
Multiple maps can exist for “equal” objects- Dependent on order in which fields are added
to the object- ie. X then Y, or Y then X
Map
Elements
Extra Props
1:
2:
3:
...
...
32:
Map
1:
Length
2:
Fixed Array
Fixed Array
Map
© 2014 IBM Corporation77
Polymorphism and JIT Compilation Functions are stored in JavaScript objects as fields- No fixed set of methods for an object
● Objects are not typed, so data much be checked to determine how to handle iteg. the '+' operator:
- number + number → addition- string involved? → concatenation- objects involved? → convert to primitives then addition or concatenation
eg. property load:- Load prototype object- Load getter method- Load callback function
● Therefore not possible to determine what instructions to use just from the source code
© 2014 IBM Corporation78
Approach to JIT Compilation V8 JavaScript engine has two compilers
Full Compiler- Compiles JavaScript to native code on first execution- No bytecode stage, and no real optimization applied- Implements a Polymorphic Inline Cache (PIC)
Crankshaft- Execution counter based compilation strategy
Also supports on-stack replacement for code with hot loops- Compilation is done in the execution path- Optimized for types present in the PIC
© 2014 IBM Corporation79
Polymorphism and Garbage Collection
Implements Generational Garbage Collection, similar to the JVM
– New space, Old space, Large Object space, Remembered sets
– Additional JavaScript specific areas: map space, cell space, property cell space
– Implements concurrent mark/sweep capabilities
Root scan based on Global objects and local variables on the stack
– Reference tree built by following object references to further objects
– However... how do we know which variables are Objects rather than data?
• Solution is tagged pointers – use of 01 in the low order bits to denote a pointer
© 2014 IBM Corporation80
JavaScript on the JVM?
© 2014 IBM Corporation81
JavaScript on the JVM Rhino was bundled in JDK6
- Based on the Mozilla Rhino engine- Allowed JavaScript to be embedded in Java, and for JavaScript to call out to Java- Provided jrunscript command line utility
Nashorn replaces JavaScript in JDK8- Supports full ECMAScript 5.1 specification- Exploits invokedynamic to provide 2x to 10x better performance than Rhino- Provides jjs command line utility
© 2014 IBM Corporation82
JavaScript on the JVM
Rhino was bundled in JDK6ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
© 2014 IBM Corporation83
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
JavaScript on the JVM
© 2014 IBM Corporation84
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
JavaScript on the JVM
© 2014 IBM Corporation85
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
JavaScript on the JVM
© 2014 IBM Corporation86
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
JavaScript on the JVM
© 2014 IBM Corporation87
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
JavaScript on the JVM
© 2014 IBM Corporation88
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
int sendVal = 7;nashorn.put("sendVal", sendVal);
nashorn.eval(" "+"var Thread = Java.type(\"java.lang.Thread\"); "+"var MyThread = Java.extend(Thread, { "+" run: function() { "+" print(\"Run in separate thread\"); "+" } "+"}); "+"var th = new MyThread(); "+ "th.start(); "+ "th.join(); "+"var resultVal = sendVal + 3;");
System.out.println(nashorn.get("resultVal");
JavaScript on the JVM
© 2014 IBM Corporation89
Introduction to Avatar.js Support for Node.js on Nashorn
Binary builds available from Maven– Avatar-js.jar– Avatar-js library (64bit)
Number of common NPM modules are supported
NPM required to dependencies
Issues for native NPMs– No native V8 APIs
From https://avatar-js.java.net/
© 2014 IBM Corporation90
Avatar.js vs Node.js Running Octane r33
– The “SpecJVM98” of the JavaScript world– Actually a JavaScript benchmark rather than a Node.js benchmark– So more comparing Nashorn to V8
Run on a 8 CPU Windows using:– Node.js v0.10.31– HotSpot 8u20
Settings are “out of the box” with no attempt to tune
© 2014 IBM Corporation91
Avatar.js running Octane Bencmark
Avatar.js
● Duration: 1m 56s
● Peak memory: 2830MB
© 2014 IBM Corporation92
Node.js running Octane Bencmark
Node.js
● Duration: 24s
● Peak memory: 268MB
© 2014 IBM Corporation93
Avatar.js vs Node.js Memory Usage
Avatar.js
● Duration: 1m 56s
● Peak memory: 2830MB
Node.js
● Duration: 24s
● Peak memory: 268MB
Node.js is 4.8x faster
Avatar.js is >10x bigger
© 2014 IBM Corporation94
Avatar.js vs Node.js: Garbage Collection Avatar.js peak is:
– 920MB / 1.85GB
Node.js peak is:– 200MB / 220MB
Additional 700+MB of Object Heap
Additional 1GB of non-Object Heap
© 2014 IBM Corporation95
Avatar.js vs Node.js: Stack Traces
Interpretation of JavaScript at the Java layer means stacks are large and anonymous
© 2014 IBM Corporation96
Summary JavaScript has a large amount of interest and is growing
– Fits well for web applications and code sharing between server and browser– Async IO and event loop model makes it easy to write scalable applications
Weak typing and dynamic linkage makes programming easier, but introduces challenges– Errors found during compilation for strongly typed languages are found at runtime– JIT compilation loves certainty, which is removed
Nashorn and Avatar.js introduces JavaScript to the JVM– Adds interoperability– … but suffers from the same challenges
© 2014 IBM Corporation97
IBM Developer Kits for Javaibm.biz/javasdk
WebShere Liberty Profilewasdev.net
IBM Bluemixibm.com/bluemix
IBM Developer Kits for Node.jsibm.biz/nodesdk
© 2014 IBM Corporation98
Questions?
© 2014 IBM Corporation
ibm.biz/javaone2014Visit Booth 5511 to learn about Cloud, DevOps and Mobile solutions
www.ibm.com/developer
Discovernew technical resources.
Developyour coding skills.
Connectwith developers.
© 2014 IBM Corporation100
Copyright and Trademarks
© IBM Corporation 2013. All Rights Reserved.
IBM, the IBM logo, and ibm.com are trademarks or registered trademarks of International Business Machines Corp., and registered in many jurisdictions worldwide.
Other product and service names might be trademarks of IBM or other companies.
A current list of IBM trademarks is available on the Web – see the IBM “Copyright and trademark information” page at URL: www.ibm.com/legal/copytrade.shtml