KEMBAR78
JavaOne 2014: Java vs JavaScript | PDF
Chris Bailey – IBM Runtime Monitoring and Diagnostics 
1st October 2014 
Java vs JavaScript 
Head to Head 
Document number 
© 2014 IBM Corporation
© 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
A Quick Survey 
© 2014 3 IBM Corporation
What languages do you program in? 
Java JavaScript Both 
60 
50 
40 
30 
20 
10 
0 
Percentage of Audience 
© 2014 4 IBM Corporation
What runtimes do you use? 
Server Java Applets JS in Browser Node.js Rhino Nashorn Avatar.js 
100 
90 
80 
70 
60 
50 
40 
30 
20 
10 
0 
Percentage of Audience 
© 2014 5 IBM Corporation
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: 
- baileyc@uk.ibm.com 
- http://www.linkedin.com/in/chrisbaileyibm 
- http://www.slideshare.net/cnbailey/ 
- @Chris__Bailey 
© 2014 6 IBM Corporation
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 7 IBM Corporation
Language Adoption 
© 2014 8 IBM Corporation
GitHub Adoption: Java 
© 2014 9 IBM Corporation
GitHub Adoption: JavaScript 
GitHut Adoption 
© 2014 10 IBM Corporation
Modulecounts.com 
© 2014 11 IBM Corporation
StackOverFlow Survey 
© 2014 12 IBM Corporation
Tiobe Programming Community Index 
● Ratings based on the number of skilled engineers, courses and third party vendors. 
© 2014 13 IBM Corporation
Indeed.com Job Trends 
© 2014 14 IBM Corporation
Indeed.com Job Trends 
© 2014 15 IBM Corporation
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 16 IBM Corporation
Deployment Modes 
© 2014 17 IBM Corporation
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 described 
below, even after updating to 7u11. This will help mitigate other Java vulnerabilities that 
may 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 18 IBM Corporation
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 19 IBM Corporation
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 
Node Standard Library 
Node Bindings 
V8 libuv 
JavaScript 
C 
© 2014 20 IBM Corporation
Async I/O Model 
© 2014 21 IBM Corporation
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 22 IBM Corporation
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 23 IBM Corporation
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 24 IBM Corporation
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 25 IBM Corporation
HTTP Server Example 
var 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 26 IBM Corporation
HTTP Server Example with Clustering 
var 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 27 IBM Corporation
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 28 IBM Corporation
© 2014 29 IBM Corporation
© 2014 30 IBM Corporation
© 2014 31 IBM Corporation
© 2014 32 IBM Corporation
© 2014 33 IBM Corporation
© 2014 34 IBM Corporation
© 2014 35 IBM Corporation
© 2014 36 IBM Corporation
© 2014 37 IBM Corporation
© 2014 38 IBM Corporation
© 2014 39 IBM Corporation
© 2014 40 IBM Corporation
© 2014 41 IBM Corporation
© 2014 42 IBM Corporation
© 2014 43 IBM Corporation
© 2014 44 IBM Corporation
© 2014 45 IBM Corporation
© 2014 46 IBM Corporation
© 2014 47 IBM Corporation
© 2014 48 IBM Corporation
© 2014 49 IBM Corporation
© 2014 50 IBM Corporation
© 2014 51 IBM Corporation
© 2014 52 IBM Corporation
© 2014 53 IBM Corporation
© 2014 54 IBM Corporation
© 2014 55 IBM Corporation
© 2014 56 IBM Corporation
© 2014 57 IBM Corporation
© 2014 58 IBM Corporation
© 2014 59 IBM Corporation
© 2014 60 IBM Corporation
© 2014 61 IBM Corporation
© 2014 62 IBM Corporation
© 2014 63 IBM Corporation
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 64 IBM Corporation
WebApp Performance 
© 2014 65 IBM Corporation
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 66 IBM Corporation
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 67 IBM Corporation
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 68 IBM Corporation
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 69 IBM Corporation
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 70 IBM Corporation
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 71 IBM Corporation
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 72 IBM Corporation
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 73 IBM Corporation
Under the Hood 
© 2014 74 IBM Corporation
Polymorphism and Object Representation 
Integer Class 
Integer Object Name: Integer 
Class pointer 
Class pointer 
Class pointer 
Class pointer 
Flags 
Flags 
Flags 
Flags 
Locks 
Locks 
Locks 
Locks 
int 
int 
int 
int 
Super Class 
Method Table 
Field Table 
Constant Pool 
Object Offsets 
... 
 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 75 IBM Corporation
Polymorphism and Object Representation 
Map 
Field: offset 
Field: offset 
Field: offset 
Fixed Array 
Map 
Length 
Fixed Array 
Map 
1: 
2: 
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 
Extra Props 
Elements 
1: 
2: 
3: 
... 
... 
32: 
© 2014 76 IBM Corporation
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 it 
eg. 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 77 IBM Corporation
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 78 IBM Corporation
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 79 IBM Corporation
JavaScript on the JVM? 
© 2014 80 IBM Corporation
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 81 IBM Corporation
JavaScript on the JVM 
 SRcrhiinpot Ewnagsi nbeuMnadnleadge inr JsDcKri6ptEngineManager = 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 82 IBM Corporation
JavaScript on the JVM 
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"); 
© 2014 83 IBM Corporation
JavaScript on the JVM 
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"); 
© 2014 84 IBM Corporation
JavaScript on the JVM 
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"); 
© 2014 85 IBM Corporation
JavaScript on the JVM 
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"); 
© 2014 86 IBM Corporation
JavaScript on the JVM 
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"); 
© 2014 87 IBM Corporation
JavaScript on the JVM 
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"); 
© 2014 88 IBM Corporation
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 89 IBM Corporation
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 90 IBM Corporation
Avatar.js running Octane Bencmark 
Avatar.js 
● Duration: 1m 56s 
● Peak memory: 2830MB 
© 2014 91 IBM Corporation
Node.js running Octane Bencmark 
Node.js 
● Duration: 24s 
● Peak memory: 268MB 
© 2014 92 IBM Corporation
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 93 IBM Corporation
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 94 IBM Corporation
Avatar.js vs Node.js: Stack Traces 
 Interpretation of JavaScript at the Java layer means stacks are large and anonymous 
© 2014 95 IBM Corporation
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 96 IBM Corporation
IBM Developer Kits for Java 
ibm.biz/javasdk 
WebShere Liberty Profile 
wasdev.net 
IBM Bluemix 
ibm.com/bluemix 
IBM Developer Kits for Node.js 
ibm.biz/nodesdk 
© 2014 97 IBM Corporation
Questions? 
© 2014 98 IBM Corporation
www.ibm.com/developer 
Discover 
new technical resources. 
ibm.biz/javaone2014 
Visit Booth 5511 to learn about Cloud, DevOps and Mobile solutions 
© 2014 IBM Corporation 
Develop 
your coding skills. 
Connect 
with developers.
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 
© 2014 100 IBM Corporation

JavaOne 2014: Java vs JavaScript

  • 1.
    Chris Bailey –IBM Runtime Monitoring and Diagnostics 1st October 2014 Java vs JavaScript Head to Head Document number © 2014 IBM Corporation
  • 2.
    © 2014 IBMCorporation 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
  • 3.
    A Quick Survey © 2014 3 IBM Corporation
  • 4.
    What languages doyou program in? Java JavaScript Both 60 50 40 30 20 10 0 Percentage of Audience © 2014 4 IBM Corporation
  • 5.
    What runtimes doyou use? Server Java Applets JS in Browser Node.js Rhino Nashorn Avatar.js 100 90 80 70 60 50 40 30 20 10 0 Percentage of Audience © 2014 5 IBM Corporation
  • 6.
    Introduction to thespeaker  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: - baileyc@uk.ibm.com - http://www.linkedin.com/in/chrisbaileyibm - http://www.slideshare.net/cnbailey/ - @Chris__Bailey © 2014 6 IBM Corporation
  • 7.
    Goals of thistalk ● Langage Adoption ● Deployment Modes ● Introduction to Node.js ● Asynchronous IO ● WebApplication Performance ● Under the Hood of Node.js ● JavaScript on the JVM © 2014 7 IBM Corporation
  • 8.
    Language Adoption ©2014 8 IBM Corporation
  • 9.
    GitHub Adoption: Java © 2014 9 IBM Corporation
  • 10.
    GitHub Adoption: JavaScript GitHut Adoption © 2014 10 IBM Corporation
  • 11.
    Modulecounts.com © 201411 IBM Corporation
  • 12.
    StackOverFlow Survey ©2014 12 IBM Corporation
  • 13.
    Tiobe Programming CommunityIndex ● Ratings based on the number of skilled engineers, courses and third party vendors. © 2014 13 IBM Corporation
  • 14.
    Indeed.com Job Trends © 2014 14 IBM Corporation
  • 15.
    Indeed.com Job Trends © 2014 15 IBM Corporation
  • 16.
    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 16 IBM Corporation
  • 17.
    Deployment Modes ©2014 17 IBM Corporation
  • 18.
    Usage in theBrowser ● 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 described below, even after updating to 7u11. This will help mitigate other Java vulnerabilities that may 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 18 IBM Corporation
  • 19.
    Usage on theServer ● 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 19 IBM Corporation
  • 20.
    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 Node Standard Library Node Bindings V8 libuv JavaScript C © 2014 20 IBM Corporation
  • 21.
    Async I/O Model © 2014 21 IBM Corporation
  • 22.
    Typical approach toIO  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 22 IBM Corporation
  • 23.
    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 23 IBM Corporation
  • 24.
    Drawbacks of AsynchronousIO  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 24 IBM Corporation
  • 25.
    JavaScript and AsynchronousIO  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 25 IBM Corporation
  • 26.
    HTTP Server Example var 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 26 IBM Corporation
  • 27.
    HTTP Server Examplewith Clustering var 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 27 IBM Corporation
  • 28.
    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 28 IBM Corporation
  • 29.
    © 2014 29IBM Corporation
  • 30.
    © 2014 30IBM Corporation
  • 31.
    © 2014 31IBM Corporation
  • 32.
    © 2014 32IBM Corporation
  • 33.
    © 2014 33IBM Corporation
  • 34.
    © 2014 34IBM Corporation
  • 35.
    © 2014 35IBM Corporation
  • 36.
    © 2014 36IBM Corporation
  • 37.
    © 2014 37IBM Corporation
  • 38.
    © 2014 38IBM Corporation
  • 39.
    © 2014 39IBM Corporation
  • 40.
    © 2014 40IBM Corporation
  • 41.
    © 2014 41IBM Corporation
  • 42.
    © 2014 42IBM Corporation
  • 43.
    © 2014 43IBM Corporation
  • 44.
    © 2014 44IBM Corporation
  • 45.
    © 2014 45IBM Corporation
  • 46.
    © 2014 46IBM Corporation
  • 47.
    © 2014 47IBM Corporation
  • 48.
    © 2014 48IBM Corporation
  • 49.
    © 2014 49IBM Corporation
  • 50.
    © 2014 50IBM Corporation
  • 51.
    © 2014 51IBM Corporation
  • 52.
    © 2014 52IBM Corporation
  • 53.
    © 2014 53IBM Corporation
  • 54.
    © 2014 54IBM Corporation
  • 55.
    © 2014 55IBM Corporation
  • 56.
    © 2014 56IBM Corporation
  • 57.
    © 2014 57IBM Corporation
  • 58.
    © 2014 58IBM Corporation
  • 59.
    © 2014 59IBM Corporation
  • 60.
    © 2014 60IBM Corporation
  • 61.
    © 2014 61IBM Corporation
  • 62.
    © 2014 62IBM Corporation
  • 63.
    © 2014 63IBM Corporation
  • 64.
    JavaScript and AsynchronousI/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 64 IBM Corporation
  • 65.
    WebApp Performance ©2014 65 IBM Corporation
  • 66.
    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 66 IBM Corporation
  • 67.
    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 67 IBM Corporation
  • 68.
    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 68 IBM Corporation
  • 69.
    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 69 IBM Corporation
  • 70.
    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 70 IBM Corporation
  • 71.
    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 71 IBM Corporation
  • 72.
    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 72 IBM Corporation
  • 73.
    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 73 IBM Corporation
  • 74.
    Under the Hood © 2014 74 IBM Corporation
  • 75.
    Polymorphism and ObjectRepresentation Integer Class Integer Object Name: Integer Class pointer Class pointer Class pointer Class pointer Flags Flags Flags Flags Locks Locks Locks Locks int int int int Super Class Method Table Field Table Constant Pool Object Offsets ...  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 75 IBM Corporation
  • 76.
    Polymorphism and ObjectRepresentation Map Field: offset Field: offset Field: offset Fixed Array Map Length Fixed Array Map 1: 2: 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 Extra Props Elements 1: 2: 3: ... ... 32: © 2014 76 IBM Corporation
  • 77.
    Polymorphism and JITCompilation  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 it eg. 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 77 IBM Corporation
  • 78.
    Approach to JITCompilation  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 78 IBM Corporation
  • 79.
    Polymorphism and GarbageCollection  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 79 IBM Corporation
  • 80.
    JavaScript on theJVM? © 2014 80 IBM Corporation
  • 81.
    JavaScript on theJVM  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 81 IBM Corporation
  • 82.
    JavaScript on theJVM  SRcrhiinpot Ewnagsi nbeuMnadnleadge inr JsDcKri6ptEngineManager = 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 82 IBM Corporation
  • 83.
    JavaScript on theJVM 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"); © 2014 83 IBM Corporation
  • 84.
    JavaScript on theJVM 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"); © 2014 84 IBM Corporation
  • 85.
    JavaScript on theJVM 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"); © 2014 85 IBM Corporation
  • 86.
    JavaScript on theJVM 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"); © 2014 86 IBM Corporation
  • 87.
    JavaScript on theJVM 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"); © 2014 87 IBM Corporation
  • 88.
    JavaScript on theJVM 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"); © 2014 88 IBM Corporation
  • 89.
    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 89 IBM Corporation
  • 90.
    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 90 IBM Corporation
  • 91.
    Avatar.js running OctaneBencmark Avatar.js ● Duration: 1m 56s ● Peak memory: 2830MB © 2014 91 IBM Corporation
  • 92.
    Node.js running OctaneBencmark Node.js ● Duration: 24s ● Peak memory: 268MB © 2014 92 IBM Corporation
  • 93.
    Avatar.js vs Node.jsMemory 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 93 IBM Corporation
  • 94.
    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 94 IBM Corporation
  • 95.
    Avatar.js vs Node.js:Stack Traces  Interpretation of JavaScript at the Java layer means stacks are large and anonymous © 2014 95 IBM Corporation
  • 96.
    Summary  JavaScripthas 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 96 IBM Corporation
  • 97.
    IBM Developer Kitsfor Java ibm.biz/javasdk WebShere Liberty Profile wasdev.net IBM Bluemix ibm.com/bluemix IBM Developer Kits for Node.js ibm.biz/nodesdk © 2014 97 IBM Corporation
  • 98.
    Questions? © 201498 IBM Corporation
  • 99.
    www.ibm.com/developer Discover newtechnical resources. ibm.biz/javaone2014 Visit Booth 5511 to learn about Cloud, DevOps and Mobile solutions © 2014 IBM Corporation Develop your coding skills. Connect with developers.
  • 100.
    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 © 2014 100 IBM Corporation