SlideShare a Scribd company logo
1 of 90
Download to read offline
What’s Next for the 
JVM 
Charles Oliver Nutter 
@headius
Background
Java 
• Released in 1995 
• Major library enhancements in 1.2 
(1998) 
• JIT compiler in 1.3 (2000) 
• Two-year cycle…until 1.6 (2006)
Sun Versus Apache 
• Apache wanted TCK to test Harmony 
• Sun could/would not release TCK 
• Apache retaliated by voting no on Java 
7 
• Java was stuck at 1.6 for five years
•OPurshaesc Jlaeva 7T tharokugeh JsC PO, agvaiensrt 
Apache 
• Oh noes…they are evil like we 
thought! 
• Doubles down on OpenJDK 
• Ok, more support, more resources ++ 
• Back to two-year cycle, aggressive 
features 
• Invokedynamic, lambda, modules, 
generics
OpenJDK Commits
OpenJDK Community 
• Dozens of companies contributing now 
• Most JVMs are OpenJDK-based 
• Former competitors enhancing 
OpenJDK 
• It’s a big ol’ OSS love-fest
kbarrett kbr kcr kevinw khazra kizune klooney klward kmiller kmo kselle kshefov ksrini kurosaki kurt kvn kwwong lagergren lana lancea landonf
We Like the JVM
No platform-specific 
compilation needed.
No native library 
dependencies
Optimizing JIT 
compiler
Magical black box 
that runs our code
Things We Like About 
JVM 
• Bytecode intermediate form 
• Freedom from native libraries 
• Optimizing JIT 
• It just works (usually)
Things That Make 
JRuby Difficult 
• JVM bytecode tailored to Java features 
• Native libraries too hard to use 
• Black box forces us to guess and pray
InvokeDynamic
History 
• JVM authors mentioned non-Java 
languages 
• Language authors have targeted JVM 
• Hundreds of JVM languages now 
• But JVM was a mismatch for many of 
them 
• Usually required tricks that defeated 
JVM optimizations 
• Or required features JDK could not 
provide
JVM Opcodes 
Invocation 
invokevirtual 
invokeinterface 
invokestatic 
invokespecial 
Field Access 
getfield 
setfield 
getstatic 
setstatic 
Array Access 
*aload 
*astore 
b,s,c,i,l,d,f,a 
Stack Local Vars 
Flow Control 
Allocation 
Boolean and Numeric
"In the future, we will consider bounded extensions to the Java Virtual 
Machine to provide better support for other languages." 
- JVM Specification First Edition (1997), preface
Goals of JSR 292 
• A user-definable bytecode 
• Full freedom to define VM behavior 
• Fast method pointers + adapters 
• Caching and invalidation 
• Avoid future modifications
Invoke 
// Static 
System.currentTimeMillis() 
Math.log(1.0)
Invoke 
// Static 
System.currentTimeMillis() 
Math.log(1.0) 
// Virtual 
"hello".toUpperCase() 
System.out.println()
Invoke 
// Static 
System.currentTimeMillis() 
Math.log(1.0) 
// Virtual 
"hello".toUpperCase() 
System.out.println() 
// Interface 
myList.add("happy happy") 
myRunnable.run()
Invoke 
// Static 
System.currentTimeMillis() 
Math.log(1.0) 
// Virtual 
"hello".toUpperCase() 
System.out.println() 
// Interface 
myList.add("happy happy") 
myRunnable.run() 
// Constructor and super
// Static 
invokestatic java/lang/System.currentTimeMillis:()J 
invokestatic java/lang/Math.log:(D)D 
invokestatic 
// Virtual 
invokevirtual java/lang/String.toUpperCase:()Ljava/lang/String; 
invokevirtual 
invokevirtual java/io/PrintStream.println:()V 
// Interface 
invokeinterface 
invokeinterface java/util/List.add:(Ljava/lang/Object;)Z 
invokeinterface java/lang/Runnable.add:()V 
invokespecial 
// Special 
invokespecial java/util/ArrayList.<init>:()V 
invokespecial java/lang/Object.equals:(java/lang/Object)Z
invokestatic 
1. Confirm arguments are of correct 
type 
2. Look up method on Java class 
3. Cache method 
4. Invoke method 
invokevirtual 
1. Confirm object is of correct type 
2. Confirm arguments are of correct type 
3. Look up method on Java class 
4. Cache method 
5. Invoke method 
invokeinterface 
1. Confirm object’s type implements interface 
2. Confirm arguments are of correct type 
3. Look up method on Java class 
4. Cache method 
5. Invoke method 
invokespecial 
1. Confirm object is of correct type 
2. Confirm arguments are of correct type 
3. Confirm target method is visible 
4. Look up method on Java class 
5. Cache method 
6. Invoke method 
invokestatic 
invokevirtual 
invokeinterface 
invokespeciianlvokedynamic 
1. Call your bootstrap code 
2. Bootstrap wires up a target function 
3. Target function invoked directly until you change it
invokedynamic bytecode 
target method 
method handles
What Can It Do?
Indy Languages 
• New language impls 
• JavaScript: Dyn.js and Nashorn 
• Redline Smalltalk 
• Improved language performance 
• JRuby, Groovy, Jython 
• Java features too!
Indy in JRuby 
• Method dispatch 
• Look up method, cache, invalidate if 
class changes or a new type is seen 
• Constant lookup 
• Retrieve constant, cache, invalidate if 
redefined
1.346071 
JRuby/Java 6 JRuby/Java 7 
Times Faster than Ruby 1.9.3 
1.537647 
1.913565 
1.565463 
2.658063 
3.439953 
3.660331 
4.32043 
5 
3.75 
2.5 
1.25 
0 
base64 richards neural redblack
2.48 
red/black tree, pure Ruby versus native 
0.51 
0.29 
0 0.75 1.5 2.25 3 
ruby-2.0.0 + Ruby 
ruby-2.0.0 + C ext 
jruby + Ruby 
Runtime per iteration
Lambda (8) 
• Long-awaited closure support for Java 
• Similar to inner classes, but… 
• Lazily generate function class 
• Single object constructed, cached 
• All shared state passed on call stack
Collections.sort(input, (a,b)->Integer.compare(a.length(), b.length())); 
0: aload_0 
1: invokedynamic #36, 0 
6: invokestatic #37 // Comparator.sort:(…) 
9: return 
0: aload_0 
1: invokevirtual #53 // String.length:()I 
4: aload_1 
5: invokevirtual #53 // String.length:()I 
8: invokestatic #54 // Integer.compare:(II)I 
11: ireturn
Generic Specialization 
(9) 
• ArrayList<int> that actually uses int 
• Indy call site requests int-specialization 
• int version of class generated lazily 
• Working prototypes now in Valhalla
What Else? 
• JRuby working to pre-optimize more 
code 
• JVM folks working on startup time 
issues 
• What about non-JVM languages?
Native Interop
JVM World 
???? 
Native World
“If non-Java programmers find some 
library useful and easy to access, it 
should be similarly accessible to Java 
programmers.” 
- John Rose
JNI
User Code 
JNI call 
JNI impl 
Target 
Library 
Java 
C/native
public class GetPidJNI { 
public static native long getpid(); 
public static void main( String[] args ) { 
getpid(); 
} 
static { 
System.load( 
System.getProperty("user.dir") + 
"/getpidjni.dylib"); 
} 
} 
JNI
/* DO NOT EDIT THIS FILE - it is machine generated */ 
#include <jni.h> 
/* Header for class com_headius_jnr_presentation_GetPidJNI */ 
#ifndef _Included_com_headius_jnr_presentation_GetPidJNI 
#define _Included_com_headius_jnr_presentation_GetPidJNI 
#ifdef __cplusplus 
extern "C" { 
#endif 
/* 
* Class: com_headius_jnr_presentation_GetPidJNI 
* Method: getpid 
* Signature: ()J 
*/ 
JNIEXPORT jlong JNICALL Java_com_headius_jnr_1presentation_GetPidJNI_getpid 
(JNIEnv *, jclass); 
#ifdef __cplusplus 
} 
JNI
#include "com_headius_jnr_presentation_GetPidJNI.h" 
jlong JNICALL Java_com_headius_jnr_1presentation_GetPidJNI_getpid 
(JNIEnv *env, jclass c) { 
return getpid(); 
} 
JNI
JNI 
$ gcc -I $JAVA_HOME/include -I 
$JAVA_HOME/include/darwin -L 
$JAVA_HOME/jre/lib/ -dynamiclib -ljava 
-o getpidjni.dylib 
com_headius_jnr_presentation_GetPidJNI. 
c 
$ java -Djava.library.path=`pwd` -cp 
target/jnr_presentation-1.0- 
SNAPSHOT.jar 
com.headius.jnr_presentation.GetPidJNI
There Must Be 
A Better Way
User Code 
JNI call 
JNI impl 
Target 
Library 
Java 
C/native
User Code 
JNR stub 
JNI call 
JNI impl 
libffi 
Target 
Library 
Java 
C/native
Java Native Runtime 
• Java API 
• for calling Native code 
• supported by a rich Runtime library 
• You may be familiar with JNA 
• Foreign Function Interface (FFI) 
• https://github.com/jnr
import jnr.ffi.LibraryLoader; 
import jnr.ffi.annotations.IgnoreError; 
public class GetPidJNRExample { 
public interface GetPid { 
long getpid(); 
} 
public static void main( String[] args ) { 
GetPid getpid = LibraryLoader 
.create(GetPid.class) 
.load("c"); 
getpid.getpid(); 
} 
} 
JNR
Layered Runtime 
etc etc 
jnr-ffi 
jffi 
libffi 
jnr-posix jnr-constants 
jnr-enxio 
jnr-x86asm 
jnr-unixsocket
Platforms 
• Darwin (OS X): universal (+ppc?) 
• Linux: i386, x86_64, arm, ppc, ppc64, s390x 
• Windows: i386, x86_64 
• FreeBSD, OpenBSD: i386, x86_64 
• SunOS: i386, x86_64, sparc, sparcv9 
• AIX: ppc 
• OpenVMS, AS/400: builds out there somewhere 
• If your platform isn't here, contribute a build
jnr-ffi 
• User-oriented API 
• Roughly equivalent to what JNA gives 
you 
• Functions, structs, callbacks, memory 
• https://github.com/jnr/jnr-ffi
jnr-posix 
• Pre-bound set of POSIX functions 
• Mostly driven by what JRuby, Jython 
use 
• Goal: 100% of POSIX bound to Java
public int getpgid(); 
public int getpgid(int i); 
public int getpgrp(); 
public int getpid(); 
public int getppid(); 
public Passwd getpwent(); 
public Passwd getpwuid(int i); 
public Passwd getpwnam(String string); 
public Group getgrgid(int i); 
public Group getgrnam(String string); 
public int getuid(); 
public boolean isatty(FileDescriptor fd); 
public int kill(int i, int i1); 
public int symlink(String string, String string1); 
public int link(String string, String string1); 
public String readlink(String string) throws IOException; 
public String getenv(String string); 
public int setenv(String string, String string1, int i); 
public int unsetenv(String string); 
public int getpriority(int i, int i1); 
public int setpriority(int i, int i1, int i2); 
public int setuid(int i); 
public FileStat stat(String string); 
public int stat(String string, FileStat fs); 
public int umask(int i);
POSIX posix = POSIXFactory.getPOSIX( 
new MyPOSIXHandler(this), 
isNativeEnabled);
jnr-enxio 
• Extended Native X-platform IO 
• NIO-compatible JNR-backed IO library 
• Read, write, select (kqueue, epoll, 
etc) 
• Low-level fcntl control 
• https://github.com/jnr/jnr-enxio
public class NativeSocketChannel 
extends AbstractSelectableChannel 
implements ByteChannel, NativeSelectableChannel { 
public NativeSocketChannel(int fd); 
public NativeSocketChannel(int fd, int ops); 
public final int validOps(); 
public final int getFD(); 
public int read(ByteBuffer dst) throws IOException; 
public int write(ByteBuffer src) throws IOException 
public void shutdownInput() throws IOException; 
public void shutdownOutput() throws IOException; 
}
jnr-unixsocket 
• UNIX sockets for NIO 
• Built atop jnr-enxio 
• Fully selectable, etc 
• https://github.com/jnr/jnr-unixsocket
What Else? 
• NIO, NIO.2 
• Native IO, symlinks, FS-walking, 
• Unmanaged memory 
• Selectable stdio, process IO 
• Low-level or other sockets (UNIX, ICMP, 
...) 
• New APIs (graphics, crypto, OS, ...)
Performance 
• Generated code leading to JNI call 
• Generated assembly version of native 
part 
• jnr-x86asm: Generate and link ASM 
• Used internally by jnr 
• https://github.com/jnr/jnr-x86asm
100000 
10000 
1000 
100 
10 
1 
JNA getpid JNR getpid 
getpid calls, 100M times
import jnr.ffi.LibraryLoader; 
import jnr.ffi.annotations.IgnoreError; 
public class GetPidJNRExample { 
public interface GetPid { 
@IgnoreError 
long getpid(); 
} 
public static void main( String[] args ) { 
GetPid getpid = LibraryLoader 
.create(GetPid.class) 
.load("c"); 
getpid.getpid(); 
} 
@IgnoreError
2500 
2000 
1500 
1000 
500 
0 
JNR getpid JNR getpid @IgnoreError 
getpid calls, 100M times
But There's More to 
2500 
2000 
1500 
1000 
500 
0 
Do 
JNR getpid JNI JNR @IgnoreError GCC -O3 
getpid calls, 100M times
Project Panama 
• JEP-191: FFI for the JVM 
• Native interop at platform level 
• JIT intelligence 
• Security 
• Native method handles 
• Native memory layout and manipulation
Truffle and Graal
Out of our control 
Written in C++ 
JVM 
Language 
JVM 
Bytecode 
Bytecode 
Interpreter 
Bytecode 
JIT 
Native 
Code
What If… 
• The JVM’s JIT optimizer were written in 
Java 
• You could customize how the JIT works 
for your language or library 
• JITed code could directly make native 
calls
Graal 
• A 100% Java-based JIT framework 
• Grew out of the 100% Java “Maxine” 
JVM 
• Emits assembly or HotSpot IR 
• Directly control code generation 
• Route around JVM bytecode 
• http://openjdk.java.net/projects/graal/
Language 
Plain Java APIs 
Under your control 
JVM 
Graal 
Intermediate 
Representati 
on 
Graal 
Optimizer 
Native 
Code 
Your 
Optimizations
However… 
• Not everyone is a compiler writer 
• Graal’s IR is low-level and nontrivial 
• Need to understand JVM internals 
• Need some understanding of CPU
The Dream 
• Design your language 
• ??? 
• PROFIT
What We Want 
• Design your language 
• Write an interpreter 
• PROFIT
Truffle 
• Language framework built on Graal 
• Designed to fulfill the dream 
• Implement interpreter 
• Truffle feeds that to backend 
• No compiler expertise needed 
• https://wiki.openjdk.java.net/display/Graal/Truffle+FAQ+and+Guid 
elines
JVM 
Language 
Truffle 
AST 
Graal 
Intermediate 
Representatio 
n 
Graal 
Optimize 
r 
Native 
Code 
All we need
The Payoff 
• RubyTruffle now part of JRuby 
• Released in JRuby 9k 
• Many languages in the works 
• May become part of OpenJDK 
releases? 
• Forcing Hotspot folks to push harder
What Have We 
Learned?
The JVM has its 
problems, but we can 
fix them.
This is all open 
source…you can help
Nothing is 
impossible.
Thank you! 
• Charles Oliver Nutter 
• @headius, headius@headius.com 
• http://blog.headius.com

More Related Content

What's hot

JRuby 9000 - Taipei Ruby User's Group 2015
JRuby 9000 - Taipei Ruby User's Group 2015JRuby 9000 - Taipei Ruby User's Group 2015
JRuby 9000 - Taipei Ruby User's Group 2015Charles Nutter
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsNikita Lipsky
 
Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013Charles Nutter
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)goccy
 
Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012Anton Arhipov
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)ngotogenome
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediZeroTurnaround
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Christian Schneider
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingHaim Yadid
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyMatthew Gaudet
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMKris Mok
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 
Invoke dynamic your api to hotspot
Invoke dynamic your api to hotspotInvoke dynamic your api to hotspot
Invoke dynamic your api to hotspotBoundary
 
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...Nikita Lipsky
 
Как мы взломали распределенные системы конфигурационного управления
Как мы взломали распределенные системы конфигурационного управленияКак мы взломали распределенные системы конфигурационного управления
Как мы взломали распределенные системы конфигурационного управленияPositive Hack Days
 
Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...
Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...
Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...Positive Hack Days
 
A Taste of Clojure
A Taste of ClojureA Taste of Clojure
A Taste of ClojureDavid Leung
 

What's hot (20)

JRuby 9000 - Taipei Ruby User's Group 2015
JRuby 9000 - Taipei Ruby User's Group 2015JRuby 9000 - Taipei Ruby User's Group 2015
JRuby 9000 - Taipei Ruby User's Group 2015
 
Ahead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java ApplicationsAhead-Of-Time Compilation of Java Applications
Ahead-Of-Time Compilation of Java Applications
 
Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
 
Shark
Shark Shark
Shark
 
Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012Mastering java bytecode with ASM - GeeCON 2012
Mastering java bytecode with ASM - GeeCON 2012
 
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
Running Ruby on Solaris (RubyKaigi 2015, 12/Dec/2015)
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profiling
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRuby
 
Intrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VMIntrinsic Methods in HotSpot VM
Intrinsic Methods in HotSpot VM
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 
Invoke dynamic your api to hotspot
Invoke dynamic your api to hotspotInvoke dynamic your api to hotspot
Invoke dynamic your api to hotspot
 
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
 
Как мы взломали распределенные системы конфигурационного управления
Как мы взломали распределенные системы конфигурационного управленияКак мы взломали распределенные системы конфигурационного управления
Как мы взломали распределенные системы конфигурационного управления
 
Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...
Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...
Изучаем миллиард состояний программы на уровне профи. Как разработать быстрый...
 
A Taste of Clojure
A Taste of ClojureA Taste of Clojure
A Taste of Clojure
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 

Similar to GOTO Night with Charles Nutter Slides

Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9Ivan Krylov
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292ytoshima
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineChun-Yu Wang
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaKeith Bennett
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Rittercatherinewall
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVAHome
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugketan_patel25
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
Charles nutter star techconf 2011 - jvm languages
Charles nutter   star techconf 2011 - jvm languagesCharles nutter   star techconf 2011 - jvm languages
Charles nutter star techconf 2011 - jvm languagesStarTech Conference
 
Toward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareToward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareZongXian Shen
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Anton Arhipov
 

Similar to GOTO Night with Charles Nutter Slides (20)

Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
Invokedynamic / JSR-292
Invokedynamic / JSR-292Invokedynamic / JSR-292
Invokedynamic / JSR-292
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Java >= 9
Java >= 9Java >= 9
Java >= 9
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-java
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Perl6 meets JVM
Perl6 meets JVMPerl6 meets JVM
Perl6 meets JVM
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Object Oriented Programming-JAVA
Object Oriented Programming-JAVAObject Oriented Programming-JAVA
Object Oriented Programming-JAVA
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Charles nutter star techconf 2011 - jvm languages
Charles nutter   star techconf 2011 - jvm languagesCharles nutter   star techconf 2011 - jvm languages
Charles nutter star techconf 2011 - jvm languages
 
Toward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareToward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malware
 
Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012Mastering Java Bytecode - JAX.de 2012
Mastering Java Bytecode - JAX.de 2012
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 

Recently uploaded

Theory of Machine Notes / Lecture Material .pdf
Theory of Machine Notes / Lecture Material .pdfTheory of Machine Notes / Lecture Material .pdf
Theory of Machine Notes / Lecture Material .pdfShreyas Pandit
 
Indian Tradition, Culture & Societies.pdf
Indian Tradition, Culture & Societies.pdfIndian Tradition, Culture & Societies.pdf
Indian Tradition, Culture & Societies.pdfalokitpathak01
 
Network Enhancements on BitVisor for BitVisor Summit 12
Network Enhancements on BitVisor for BitVisor Summit 12Network Enhancements on BitVisor for BitVisor Summit 12
Network Enhancements on BitVisor for BitVisor Summit 12cjchen22
 
Livre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdf
Livre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdfLivre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdf
Livre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdfsaad175691
 
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...arifengg7
 
How to Implement Effective Stormwater Management in DC
How to Implement Effective Stormwater Management in DCHow to Implement Effective Stormwater Management in DC
How to Implement Effective Stormwater Management in DCSera Engineered, LLC
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosVictor Morales
 
March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...
March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...
March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...gerogepatton
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
Pyrolysis process control: temperature control design and application for opt...
Pyrolysis process control: temperature control design and application for opt...Pyrolysis process control: temperature control design and application for opt...
Pyrolysis process control: temperature control design and application for opt...IJECEIAES
 
maths mini project ( applictions of quadratic forms and SVD ).ppt
maths mini project ( applictions of quadratic forms and SVD ).pptmaths mini project ( applictions of quadratic forms and SVD ).ppt
maths mini project ( applictions of quadratic forms and SVD ).pptManavPatane
 
Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...
Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...
Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...shreenathji26
 
Ece technical seminar topic for under graduate.pptx
Ece technical seminar topic for under graduate.pptxEce technical seminar topic for under graduate.pptx
Ece technical seminar topic for under graduate.pptxArjunPLinekaje
 
Feasibility analysis and modeling of a solar hybrid system for residential el...
Feasibility analysis and modeling of a solar hybrid system for residential el...Feasibility analysis and modeling of a solar hybrid system for residential el...
Feasibility analysis and modeling of a solar hybrid system for residential el...IJECEIAES
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSneha Padhiar
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxRomil Mishra
 
10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptx10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptxAdityaGoogle
 
Madani.store - Planning - Interview Questions
Madani.store - Planning - Interview QuestionsMadani.store - Planning - Interview Questions
Madani.store - Planning - Interview QuestionsKarim Gaber
 
AI Powered Ecover creator that creates everything that you want
AI Powered Ecover creator that creates everything that you wantAI Powered Ecover creator that creates everything that you want
AI Powered Ecover creator that creates everything that you wantsuja868966
 

Recently uploaded (20)

Theory of Machine Notes / Lecture Material .pdf
Theory of Machine Notes / Lecture Material .pdfTheory of Machine Notes / Lecture Material .pdf
Theory of Machine Notes / Lecture Material .pdf
 
Indian Tradition, Culture & Societies.pdf
Indian Tradition, Culture & Societies.pdfIndian Tradition, Culture & Societies.pdf
Indian Tradition, Culture & Societies.pdf
 
Network Enhancements on BitVisor for BitVisor Summit 12
Network Enhancements on BitVisor for BitVisor Summit 12Network Enhancements on BitVisor for BitVisor Summit 12
Network Enhancements on BitVisor for BitVisor Summit 12
 
Livre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdf
Livre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdfLivre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdf
Livre Implementing_Six_Sigma_and_Lean_A_prac([Ron_Basu]_).pdf
 
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
Analysis and Evaluation of Dal Lake Biomass for Conversion to Fuel/Green fert...
 
How to Implement Effective Stormwater Management in DC
How to Implement Effective Stormwater Management in DCHow to Implement Effective Stormwater Management in DC
How to Implement Effective Stormwater Management in DC
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitos
 
March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...
March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...
March 2024 - Top 10 Read Articles in Artificial Intelligence and Applications...
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
Pyrolysis process control: temperature control design and application for opt...
Pyrolysis process control: temperature control design and application for opt...Pyrolysis process control: temperature control design and application for opt...
Pyrolysis process control: temperature control design and application for opt...
 
maths mini project ( applictions of quadratic forms and SVD ).ppt
maths mini project ( applictions of quadratic forms and SVD ).pptmaths mini project ( applictions of quadratic forms and SVD ).ppt
maths mini project ( applictions of quadratic forms and SVD ).ppt
 
Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...
Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...
Introduction to Artificial Intelligence: Intelligent Agents, State Space Sear...
 
Ece technical seminar topic for under graduate.pptx
Ece technical seminar topic for under graduate.pptxEce technical seminar topic for under graduate.pptx
Ece technical seminar topic for under graduate.pptx
 
Feasibility analysis and modeling of a solar hybrid system for residential el...
Feasibility analysis and modeling of a solar hybrid system for residential el...Feasibility analysis and modeling of a solar hybrid system for residential el...
Feasibility analysis and modeling of a solar hybrid system for residential el...
 
Neometrix Optical Balloon Theodolite.pptx
Neometrix Optical Balloon Theodolite.pptxNeometrix Optical Balloon Theodolite.pptx
Neometrix Optical Balloon Theodolite.pptx
 
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATIONSOFTWARE ESTIMATION COCOMO AND FP CALCULATION
SOFTWARE ESTIMATION COCOMO AND FP CALCULATION
 
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptxTriangulation survey (Basic Mine Surveying)_MI10412MI.pptx
Triangulation survey (Basic Mine Surveying)_MI10412MI.pptx
 
10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptx10 AsymmetricKey Cryptography students.pptx
10 AsymmetricKey Cryptography students.pptx
 
Madani.store - Planning - Interview Questions
Madani.store - Planning - Interview QuestionsMadani.store - Planning - Interview Questions
Madani.store - Planning - Interview Questions
 
AI Powered Ecover creator that creates everything that you want
AI Powered Ecover creator that creates everything that you wantAI Powered Ecover creator that creates everything that you want
AI Powered Ecover creator that creates everything that you want
 

GOTO Night with Charles Nutter Slides

  • 1. What’s Next for the JVM Charles Oliver Nutter @headius
  • 3.
  • 4. Java • Released in 1995 • Major library enhancements in 1.2 (1998) • JIT compiler in 1.3 (2000) • Two-year cycle…until 1.6 (2006)
  • 5. Sun Versus Apache • Apache wanted TCK to test Harmony • Sun could/would not release TCK • Apache retaliated by voting no on Java 7 • Java was stuck at 1.6 for five years
  • 6. •OPurshaesc Jlaeva 7T tharokugeh JsC PO, agvaiensrt Apache • Oh noes…they are evil like we thought! • Doubles down on OpenJDK • Ok, more support, more resources ++ • Back to two-year cycle, aggressive features • Invokedynamic, lambda, modules, generics
  • 8. OpenJDK Community • Dozens of companies contributing now • Most JVMs are OpenJDK-based • Former competitors enhancing OpenJDK • It’s a big ol’ OSS love-fest
  • 9. kbarrett kbr kcr kevinw khazra kizune klooney klward kmiller kmo kselle kshefov ksrini kurosaki kurt kvn kwwong lagergren lana lancea landonf
  • 10.
  • 11.
  • 12. We Like the JVM
  • 14. No native library dependencies
  • 16. Magical black box that runs our code
  • 17. Things We Like About JVM • Bytecode intermediate form • Freedom from native libraries • Optimizing JIT • It just works (usually)
  • 18. Things That Make JRuby Difficult • JVM bytecode tailored to Java features • Native libraries too hard to use • Black box forces us to guess and pray
  • 19.
  • 21. History • JVM authors mentioned non-Java languages • Language authors have targeted JVM • Hundreds of JVM languages now • But JVM was a mismatch for many of them • Usually required tricks that defeated JVM optimizations • Or required features JDK could not provide
  • 22. JVM Opcodes Invocation invokevirtual invokeinterface invokestatic invokespecial Field Access getfield setfield getstatic setstatic Array Access *aload *astore b,s,c,i,l,d,f,a Stack Local Vars Flow Control Allocation Boolean and Numeric
  • 23. "In the future, we will consider bounded extensions to the Java Virtual Machine to provide better support for other languages." - JVM Specification First Edition (1997), preface
  • 24. Goals of JSR 292 • A user-definable bytecode • Full freedom to define VM behavior • Fast method pointers + adapters • Caching and invalidation • Avoid future modifications
  • 25. Invoke // Static System.currentTimeMillis() Math.log(1.0)
  • 26. Invoke // Static System.currentTimeMillis() Math.log(1.0) // Virtual "hello".toUpperCase() System.out.println()
  • 27. Invoke // Static System.currentTimeMillis() Math.log(1.0) // Virtual "hello".toUpperCase() System.out.println() // Interface myList.add("happy happy") myRunnable.run()
  • 28. Invoke // Static System.currentTimeMillis() Math.log(1.0) // Virtual "hello".toUpperCase() System.out.println() // Interface myList.add("happy happy") myRunnable.run() // Constructor and super
  • 29. // Static invokestatic java/lang/System.currentTimeMillis:()J invokestatic java/lang/Math.log:(D)D invokestatic // Virtual invokevirtual java/lang/String.toUpperCase:()Ljava/lang/String; invokevirtual invokevirtual java/io/PrintStream.println:()V // Interface invokeinterface invokeinterface java/util/List.add:(Ljava/lang/Object;)Z invokeinterface java/lang/Runnable.add:()V invokespecial // Special invokespecial java/util/ArrayList.<init>:()V invokespecial java/lang/Object.equals:(java/lang/Object)Z
  • 30. invokestatic 1. Confirm arguments are of correct type 2. Look up method on Java class 3. Cache method 4. Invoke method invokevirtual 1. Confirm object is of correct type 2. Confirm arguments are of correct type 3. Look up method on Java class 4. Cache method 5. Invoke method invokeinterface 1. Confirm object’s type implements interface 2. Confirm arguments are of correct type 3. Look up method on Java class 4. Cache method 5. Invoke method invokespecial 1. Confirm object is of correct type 2. Confirm arguments are of correct type 3. Confirm target method is visible 4. Look up method on Java class 5. Cache method 6. Invoke method invokestatic invokevirtual invokeinterface invokespeciianlvokedynamic 1. Call your bootstrap code 2. Bootstrap wires up a target function 3. Target function invoked directly until you change it
  • 31. invokedynamic bytecode target method method handles
  • 32. What Can It Do?
  • 33. Indy Languages • New language impls • JavaScript: Dyn.js and Nashorn • Redline Smalltalk • Improved language performance • JRuby, Groovy, Jython • Java features too!
  • 34. Indy in JRuby • Method dispatch • Look up method, cache, invalidate if class changes or a new type is seen • Constant lookup • Retrieve constant, cache, invalidate if redefined
  • 35. 1.346071 JRuby/Java 6 JRuby/Java 7 Times Faster than Ruby 1.9.3 1.537647 1.913565 1.565463 2.658063 3.439953 3.660331 4.32043 5 3.75 2.5 1.25 0 base64 richards neural redblack
  • 36. 2.48 red/black tree, pure Ruby versus native 0.51 0.29 0 0.75 1.5 2.25 3 ruby-2.0.0 + Ruby ruby-2.0.0 + C ext jruby + Ruby Runtime per iteration
  • 37. Lambda (8) • Long-awaited closure support for Java • Similar to inner classes, but… • Lazily generate function class • Single object constructed, cached • All shared state passed on call stack
  • 38. Collections.sort(input, (a,b)->Integer.compare(a.length(), b.length())); 0: aload_0 1: invokedynamic #36, 0 6: invokestatic #37 // Comparator.sort:(…) 9: return 0: aload_0 1: invokevirtual #53 // String.length:()I 4: aload_1 5: invokevirtual #53 // String.length:()I 8: invokestatic #54 // Integer.compare:(II)I 11: ireturn
  • 39. Generic Specialization (9) • ArrayList<int> that actually uses int • Indy call site requests int-specialization • int version of class generated lazily • Working prototypes now in Valhalla
  • 40. What Else? • JRuby working to pre-optimize more code • JVM folks working on startup time issues • What about non-JVM languages?
  • 42. JVM World ???? Native World
  • 43. “If non-Java programmers find some library useful and easy to access, it should be similarly accessible to Java programmers.” - John Rose
  • 44.
  • 45.
  • 46. JNI
  • 47. User Code JNI call JNI impl Target Library Java C/native
  • 48. public class GetPidJNI { public static native long getpid(); public static void main( String[] args ) { getpid(); } static { System.load( System.getProperty("user.dir") + "/getpidjni.dylib"); } } JNI
  • 49. /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_headius_jnr_presentation_GetPidJNI */ #ifndef _Included_com_headius_jnr_presentation_GetPidJNI #define _Included_com_headius_jnr_presentation_GetPidJNI #ifdef __cplusplus extern "C" { #endif /* * Class: com_headius_jnr_presentation_GetPidJNI * Method: getpid * Signature: ()J */ JNIEXPORT jlong JNICALL Java_com_headius_jnr_1presentation_GetPidJNI_getpid (JNIEnv *, jclass); #ifdef __cplusplus } JNI
  • 50. #include "com_headius_jnr_presentation_GetPidJNI.h" jlong JNICALL Java_com_headius_jnr_1presentation_GetPidJNI_getpid (JNIEnv *env, jclass c) { return getpid(); } JNI
  • 51. JNI $ gcc -I $JAVA_HOME/include -I $JAVA_HOME/include/darwin -L $JAVA_HOME/jre/lib/ -dynamiclib -ljava -o getpidjni.dylib com_headius_jnr_presentation_GetPidJNI. c $ java -Djava.library.path=`pwd` -cp target/jnr_presentation-1.0- SNAPSHOT.jar com.headius.jnr_presentation.GetPidJNI
  • 52. There Must Be A Better Way
  • 53. User Code JNI call JNI impl Target Library Java C/native
  • 54. User Code JNR stub JNI call JNI impl libffi Target Library Java C/native
  • 55. Java Native Runtime • Java API • for calling Native code • supported by a rich Runtime library • You may be familiar with JNA • Foreign Function Interface (FFI) • https://github.com/jnr
  • 56. import jnr.ffi.LibraryLoader; import jnr.ffi.annotations.IgnoreError; public class GetPidJNRExample { public interface GetPid { long getpid(); } public static void main( String[] args ) { GetPid getpid = LibraryLoader .create(GetPid.class) .load("c"); getpid.getpid(); } } JNR
  • 57. Layered Runtime etc etc jnr-ffi jffi libffi jnr-posix jnr-constants jnr-enxio jnr-x86asm jnr-unixsocket
  • 58. Platforms • Darwin (OS X): universal (+ppc?) • Linux: i386, x86_64, arm, ppc, ppc64, s390x • Windows: i386, x86_64 • FreeBSD, OpenBSD: i386, x86_64 • SunOS: i386, x86_64, sparc, sparcv9 • AIX: ppc • OpenVMS, AS/400: builds out there somewhere • If your platform isn't here, contribute a build
  • 59. jnr-ffi • User-oriented API • Roughly equivalent to what JNA gives you • Functions, structs, callbacks, memory • https://github.com/jnr/jnr-ffi
  • 60. jnr-posix • Pre-bound set of POSIX functions • Mostly driven by what JRuby, Jython use • Goal: 100% of POSIX bound to Java
  • 61. public int getpgid(); public int getpgid(int i); public int getpgrp(); public int getpid(); public int getppid(); public Passwd getpwent(); public Passwd getpwuid(int i); public Passwd getpwnam(String string); public Group getgrgid(int i); public Group getgrnam(String string); public int getuid(); public boolean isatty(FileDescriptor fd); public int kill(int i, int i1); public int symlink(String string, String string1); public int link(String string, String string1); public String readlink(String string) throws IOException; public String getenv(String string); public int setenv(String string, String string1, int i); public int unsetenv(String string); public int getpriority(int i, int i1); public int setpriority(int i, int i1, int i2); public int setuid(int i); public FileStat stat(String string); public int stat(String string, FileStat fs); public int umask(int i);
  • 62. POSIX posix = POSIXFactory.getPOSIX( new MyPOSIXHandler(this), isNativeEnabled);
  • 63. jnr-enxio • Extended Native X-platform IO • NIO-compatible JNR-backed IO library • Read, write, select (kqueue, epoll, etc) • Low-level fcntl control • https://github.com/jnr/jnr-enxio
  • 64. public class NativeSocketChannel extends AbstractSelectableChannel implements ByteChannel, NativeSelectableChannel { public NativeSocketChannel(int fd); public NativeSocketChannel(int fd, int ops); public final int validOps(); public final int getFD(); public int read(ByteBuffer dst) throws IOException; public int write(ByteBuffer src) throws IOException public void shutdownInput() throws IOException; public void shutdownOutput() throws IOException; }
  • 65. jnr-unixsocket • UNIX sockets for NIO • Built atop jnr-enxio • Fully selectable, etc • https://github.com/jnr/jnr-unixsocket
  • 66. What Else? • NIO, NIO.2 • Native IO, symlinks, FS-walking, • Unmanaged memory • Selectable stdio, process IO • Low-level or other sockets (UNIX, ICMP, ...) • New APIs (graphics, crypto, OS, ...)
  • 67. Performance • Generated code leading to JNI call • Generated assembly version of native part • jnr-x86asm: Generate and link ASM • Used internally by jnr • https://github.com/jnr/jnr-x86asm
  • 68. 100000 10000 1000 100 10 1 JNA getpid JNR getpid getpid calls, 100M times
  • 69. import jnr.ffi.LibraryLoader; import jnr.ffi.annotations.IgnoreError; public class GetPidJNRExample { public interface GetPid { @IgnoreError long getpid(); } public static void main( String[] args ) { GetPid getpid = LibraryLoader .create(GetPid.class) .load("c"); getpid.getpid(); } @IgnoreError
  • 70. 2500 2000 1500 1000 500 0 JNR getpid JNR getpid @IgnoreError getpid calls, 100M times
  • 71. But There's More to 2500 2000 1500 1000 500 0 Do JNR getpid JNI JNR @IgnoreError GCC -O3 getpid calls, 100M times
  • 72. Project Panama • JEP-191: FFI for the JVM • Native interop at platform level • JIT intelligence • Security • Native method handles • Native memory layout and manipulation
  • 74. Out of our control Written in C++ JVM Language JVM Bytecode Bytecode Interpreter Bytecode JIT Native Code
  • 75. What If… • The JVM’s JIT optimizer were written in Java • You could customize how the JIT works for your language or library • JITed code could directly make native calls
  • 76. Graal • A 100% Java-based JIT framework • Grew out of the 100% Java “Maxine” JVM • Emits assembly or HotSpot IR • Directly control code generation • Route around JVM bytecode • http://openjdk.java.net/projects/graal/
  • 77. Language Plain Java APIs Under your control JVM Graal Intermediate Representati on Graal Optimizer Native Code Your Optimizations
  • 78. However… • Not everyone is a compiler writer • Graal’s IR is low-level and nontrivial • Need to understand JVM internals • Need some understanding of CPU
  • 79. The Dream • Design your language • ??? • PROFIT
  • 80. What We Want • Design your language • Write an interpreter • PROFIT
  • 81. Truffle • Language framework built on Graal • Designed to fulfill the dream • Implement interpreter • Truffle feeds that to backend • No compiler expertise needed • https://wiki.openjdk.java.net/display/Graal/Truffle+FAQ+and+Guid elines
  • 82. JVM Language Truffle AST Graal Intermediate Representatio n Graal Optimize r Native Code All we need
  • 83.
  • 84.
  • 85. The Payoff • RubyTruffle now part of JRuby • Released in JRuby 9k • Many languages in the works • May become part of OpenJDK releases? • Forcing Hotspot folks to push harder
  • 86. What Have We Learned?
  • 87. The JVM has its problems, but we can fix them.
  • 88. This is all open source…you can help
  • 90. Thank you! • Charles Oliver Nutter • @headius, headius@headius.com • http://blog.headius.com