4. 4
• Zing: A better JVM for the enterprise
• Azul’s enterprise JVM focused on better metrics
• Consistent performance - not just fast, always fast
• Eliminate GC as a concern for enterprise apps
• Very wide operating range
• From human-sensitive app responsiveness to low-latency
trading
• From microservices to huge in-memory apps
• Eliminates an entire class of engineering workarounds common in
Java
•Zulu Embedded: When you need embedded Support
• 100% open source, based on OpenJDK
• Certified Java SE compliant and compatible
• Verified “non-contaminating” open source license
• Identical metrics to OpenJDK and Oracle Java SE
• World-class support offerings
• Support for Linux & Windows; x86, ARM32, ARM64, PPC32,
MIPS
4
5. Java 9 -Why talking about it now?
• Release scheduled for 2017
• Lots of breaking changes
• I am from Azul Systems - maker of compliant JDKs
• Observing the process from aside, unbiased view on changes
• Not promoting nor diminishing
5
7. 6
• Reflection is disallowed from operating on non-exported types,
even with the use of setAccessible
• Jigsaw has only limited support for the dynamic introduction and
alteration of modules
• Restrictions that make interoperability with alternative modular
systems difficult.
• Source: http://wildfly.org/news/2016/12/12/Jigsaws-Missing-Pieces
Java 9 - concerns
9. 8
“There are only two kinds of languages:
the ones people complain about and the ones nobody uses.”
Bjarne Stroustrup
10. Java Timeline
JDK 6
Dec 2006
JDK 7
July
2011
JDK 8
March
2014
JDK 9
exp.
July
2017
JDK 6
Nov 2012
JDK 7
Apr
2015
JDK 8
exp.
July
2018
J2SE 1.4
Dec 2006
JDK 5
Oct 2009
9
GA
EOL
11. Java EOL & You?
EOL date
passed
Security
vulnerabilities
keep appearing
&
Sign Support
contact
Adopt OpenJDK
(Zulu, IcedTea,
homebrew builds)
Updated to latest
JDK
10
Updates needed
12. What (was) new in Java 8
• Lambdas
• Method references
• Type annotations
• Repeated annotations
• Interface a.k.a. default
methods
• Stream API
• Date Time API
• PermGen replacement (vendor
specific)
• Nashorn, JavaScript Engine
• New tools (jdeps,jjs,..)
11
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html
17. Fabric methods for collections
Instantiation of the immutable containers
16
Set<String> set = new HashSet<>();
set.add("a");
set.add("b");
set = Collections.unmodifiableSet(set);
Set<String> set = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList("a", "b")));
Set<String> set = Collections.unmodifiableSet(
new HashSet<String>() {{
add("a");
add("b");
}});
Set<String> set = Collections.unmodifiableSet(
Stream.of("a", “b").collect(toSet())
);
Set<String> set = Set.of("a", "b");
19. Stream API changes
18
• Stream::takeWhile
• A replacement for the
while (predicate_on_stream_element) { <keep processing this ordered stream>};
• Stream::dropWhile
• Some but start processing stream after the predicate
20. Stream API changes
18
• Stream::takeWhile
• A replacement for the
while (predicate_on_stream_element) { <keep processing this ordered stream>};
• Stream::dropWhile
• Some but start processing stream after the predicate
• Iterator with a predicate
• Stream::ofNullable
• Factory for a single non-null element
22. Syntax changes - Milling Project Coin
• Effectively-final variables in try-with-resources expressions
20
public static void main(String... args) throws …{
FileReader f = new FileReader(“test.txt”);
br =new BufferedReader(fr);
try (br) {
// do something
} catch (Exception ex) {
}
}
public static void main(String... args) throws …{
FileReader f = new FileReader(“test.txt");
try (br =new BufferedReader(fr)) {
// do something
} catch (Exception ex) {
}
}
23. Syntax changes - Milling Project Coin
• @SafeVarargs in private methods
• (In Java 8 it was only final and static)
class VarargsFinalOnly {
@SafeVarargs private void m(List<String>... args) { }
}
21
24. public class TypeInferrenceTest {
Map<String, String> map =
new HashMap<String, String>()
{
{
map.put("key", "value");
}
};
}
• Using diamond with anonymous classes when actual type may be
deduced
public class TypeInferrenceTest {
Map<String, String> map =
new HashMap<> ()
{
{
map.put("key", "value");
}
};
}
Syntax changes - Milling Project Coin
22
Prior to Java 9
./TypeInferrenceTest.java:7: error: cannot infer
type arguments for HashMap<K,V>
new HashMap<>()
^
reason: cannot use '<>' with anonymous inner classes
where K,V are type-variables:
K extends Object declared in class HashMap
V extends Object declared in class HashMap
1 error
http://c2.com/cgi/wiki?DoubleBraceInitialization
25. Syntax changes - Milling Project Coin
•
Can’t use single _as a name
23
// key: compiler.warn.underscore.as.identifier
// options: -source 8 -Xlint:-options
class UnderscoreAsIdentifierWarning {
String _ = null;
}
26. Process API Updates
• JEP 102: Process API Updates
• What’s new:
• Get pid for this JVM
• Get list of processes
• Operations on trees of processes
Source: http://blog.takipi.com/java-9-the-ultimate-feature-list/ 24
Process proc = Runtime.getRuntime()
.exec(new String[]{"/bin/sh",
"-c", "echo $PPID"});
if (proc.waitFor()==0) {
InputStream in = proc.getInputStream();
int available = in.available();
byte[] outputBytes = new byte[available];
in.read(outputBytes);
String pid = new String(outputBytes);
System.out.println("Your pid is " + pid)
}
System.out.println("Your pid is " + ProcessHandle.current().getPid());
27. Spin Loop Hint (JEP-285)
• Scope: latency (& performance)
• Features:
• New method j.l.Thread.onSpinWait()
• On x86 - translates into the ‘pause’ instruction
• Already used 9 times in JSR 166 for JDK9
• java/util/concurrent/locks/StampedLock.java
• java/util/concurrent/Phaser.java
• java/util/concurrent/SynchronousQueue.java
25
28. Spin Loop Hint (JEP-285)
• Scope: latency (& performance)
• Features:
• New method j.l.Thread.onSpinWait()
• On x86 - translates into the ‘pause’ instruction
• Already used 9 times in JSR 166 for JDK9
• java/util/concurrent/locks/StampedLock.java
• java/util/concurrent/Phaser.java
• java/util/concurrent/SynchronousQueue.java
class EventHandler {
volatile boolean eventNotificationNotReceived;
void waitForEventAndHandleIt() {
while ( eventNotificationNotReceived ) {
java.lang.Thread.onSpinWait();
}
readAndProcessEvent();
}
void readAndProcessEvent() {
// Read event from some source and process it
. . .
}
}
25
30. Spin Loop Hint
• Cool. I have spin loops. Wait for 9?
• May be not
• Just include the agrona library
• or look at java/org/agrona/hints/ThreadHints.java
• Works for older JDKs
27
https://github.com/real-logic/Agrona/blob/master/src/main/java/org/agrona/hints/ThreadHints.java
31. JShell
• Project Kulla http://openjdk.java.net/projects/kulla/
• In main trunk since JDK 9 EA build 90
• REPL as you know it for other languages
• Helps teaching Java class HelloWorld {
public static void main(String[] args) {
System.out.println(" ");
}
}
28
33. Garbage First is on by default
• Pros
• State-of-the-art GC in HotSpot (albeit being 14+ years old)
• Regional parallel concurrent collector
• Targeting both low pause and high throughput
• Default => Great number of users => Bugs detecter sooner => G1 will become even more robust shortly
• Cons
• Due to different characteristics it may reveal synchronisation problems in the code
• In recent years many bugs with Cassandra, Elasticsearch, Lucene were fixed in both GC and libraries.
Perhaps, other ones are yet not discovered?
• source (dated July 2015): https://groups.google.com/forum/#!topic/mechanical-sympathy/
JxsuVtIIOaY
30
34. Surviving the change of default GC
• If you used no i.e. default GC settings
• capture the ergonomics at your deployment sites
• consider explicitly setting GC flags in all deployment scripts
• If you already had selected and tuned GC flags
• No changes, old collectors not phasing out
• In any case - keep trying G1
• Understand how GC works
• Basic algorithms and associated metrics
• More reading: http://www.infoq.com/minibooks/java-garbage-collection
31
35. New JEPs briefly. Performance
• 193: Variable Handles
• 143: Improve Contended Locking
• 266: More Concurrency Updates
• 197: Segmented Code Cache
• 165: Compiler Control
• 243: Java-Level JVM Compiler
Interface
• 246: Leverage CPU Instructions
for GHASH and RSA
• 250: Store Interned Strings in
CDS Archives
• 254: Compact Strings
• 280: Indify String Concatenation
• 230: Microbenchmark Suite
32
36. 33
Unified JVM Logging
• For better diagnostics, uniform across all components
• 6 levels of logging x dozens of tags
• Output to stdout / stderr / file / rotating file
• No more badly interleaved lines
• -Xlog:help
• 11 decorators
-Xlog:classinit
-Xlog:classloaderdata
-Xlog:defaultmethods
-Xlog:itables
-Xlog:monitormismatch
-Xlog:safepoint
-Xlog:startuptime
-Xlog:vmoperation
-Xlog:vtables
-Xlog:verification
-XX:+TraceClassInitialization
-XX:+TraceClassLoaderData
-XX:+TraceDefaultMethods
-XX:+TraceItables
-XX:+TraceMonitorMismatch
-XX:+TraceSafepoint
-XX:+TraceStartupTime
-XX:+TraceVMOperation
-XX:+PrintVtables
-XX:+VerboseVerification
java -Xlog:help
40. Stack walking API
• Before 9: Throwable::getStackTrace и Thread::getStackTrace
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
• Since 9 also possible to:
StackFrame[] stack =new StackWalker().walk((s) ->
s.collect(Collectors.toArray()));
• New StackWalker class
37
47. Problems being addressed
• Java Runtime keeps getting bigger and bigger
• Java 8 profiles 1, 2, 3 provide partial solutions
• Jar / Classpath Hell
• What depends on what ..
• Optional dependancies, transitive dependancies
• Lazy class loading and initialization -> NoClassDefFoundError
• For code that escapes packages the visibility mechanism is poor - only public
• Classes from different packages “see” each other, even from different class loaders
• SecurityManager helps to protect, but it is not on by default
44
48. Wikepedia оn Jar-hell
• Accidental presence of two different versions of a library installed on a system. This will not
be considered an error by the system. Rather, the system will load classes from one or the other
library. Adding the new library to the list of available libraries instead of replacing it may result in
the application still behaving as though the old library is in use, which it may well be.
• Multiple libraries or applications require different versions of library foo. If versions of library
foo use the same class names, there is no way to load the versions of library foo with the same
classloader.
• The most complex JAR hell problems arise in circumstances that take advantage of the full
complexity of the classloading system. A Java program is not required to use only a single
"flat" classloader, but instead may be composed of several (potentially very many) nested,
cooperating classloaders. Classes loaded by different classloaders may interact in complex ways
not fully comprehended by a developer, leading to errors or bugs that are difficult to analyze,
explain, and resolve.
45
49. Jigsaw
JEP 162: Prepare for Modularization
JEP 200: The Modular JDK
JEP 220: Modular Run-Time Images
JEP 201: Modular Source Code
JEP 260: Encapsulate Most Internal
APIs
JEP 282: jlink: The Java Linker
JSR 376: Java Platform Module System
JEP 261: Module System
ModularityJava Module
46
50. Examples
47
• 01 - Classpath hell
• 02 - The simplest example with
Modules
• 03 - jimage
• 04 - Error “2 modules export the
same package into module 3”
• 05 - Working with 2 “identical”
classes in different modules
51. Example 1
src/com.azul.modules.module1/module-
info.java
module com.azul.modules.module1 {
exports com.azul.testpackage1;
}
src/com.azul.modules.module2/module-info.java
module com.azul.modules.module2 {
requires com.azul.modules.module1;
}
com.azul.modules.module1/com/azul/testpackage1/A.java
package com.azul.testpackage1;
public class B {
public static void m()
{
System.out.println("-- I am in path1.com.azul.test.B.m() ");
}
}
com.azul.modules.module2/com/azul/testpackage2/A.java
package com.azul.testpackage2;
public class A {
public static void main(String[] args) {
System.out.println("Calling from com.azul.modules.module2.com.azul.testpackage2.A.main() ");
com.azul.testpackage1.B.m();
}
}
1 2
48
53. New parameters for javac/java (2)
50
• # Packaging
• jar --create --file=mlib/module2.jar --main-
class=com.azul.testpackage2.A -C target/
com.azul.modules.module2 .
• # Run
• $j/bin/java -p target -m com.azul.modules.module2
Reference: http://openjdk.java.net/projects/jigsaw/quick-start
54. Example 2
./nashorn/src/jdk.scripting.nashorn/share/classes/module-info.java
module jdk.scripting.nashorn {
requires java.logging;
requires public java.scripting;
uses jdk.internal.dynalink.linker.GuardingDynamicLinker;
uses jdk.nashorn.internal.runtime.CodeStore;
provides javax.script.ScriptEngineFactory with
jdk.nashorn.api.scripting.NashornScriptEngineFactory;
exports jdk.nashorn.api.scripting;
exports jdk.nashorn.api.tree;
exports jdk.nashorn.internal.runtime to
jdk.scripting.nashorn.shell;
exports jdk.nashorn.internal.objects to
jdk.scripting.nashorn.shell;
exports jdk.nashorn.tools to
jdk.scripting.nashorn.shell;
}
META-INF/services
51
55. Types of modules
• Named
• Those containing module-info.class
• Automatic
• jar files placed to the module path
• Unnamed
• Contains all types in the classpath
52
56. Can modularised & non-modularised
code co-exist?
• Whatever is in classpath - going into unnamed modules
• Unnamed modules can access all named modules (requires *) /See next slide for a
special note/
• The reverse isn’t true - must specify requires unnamed or …
• jar file in --module-path is being automatically converted to a module with a name
matching the name of the jar file
• Therefore referred as automodules
• Provide transition path to jigsaw modules design
• Unnamed modules are being searched for types as a last option
53
57. Unnamed modules can access all
named modules
• Not so true since JDK9 build 118
• These modules are not accessible from unnamed modules:
java.activation - java.annotations.common - java.corba
java.transaction - java.xml.bind - java.xml.ws
• One can still add visibility with a flag like `-addmods
java.corba`
• Source: May 17th letter from Alan Bateman: http://mail.openjdk.java.net/
pipermail/jdk9-dev/2016-May/004309.html
• More info: http://openjdk.java.net/jeps/261
54
61. 58
• Consider an app with extensions
• The extension might require a different version of a module than loaded before
• The extension might require service providers
• Layer of modules encapsulates
• a module graph
• mapping from each module in that graph to a class loader
• Boot layer - created by VM at start time and suitable for most apps
• App can create a new layer - new universe of modules
• Stackable - package resolution starts with the app layer and goes down to the boot layer
Layers
68. (My) takeaways on Java 9 modules
• Purpose - explicit listing of dependancies
• Will provide new optimization paths
• Compatible with jar/cp
• OSGi compatibility and reflection are a concern
• Jigsaw - rough flight all way along, loosing features
• Lost ability to match versions
65
69. Jigsaw - links
• If you google it - discard all posts before 2014, probably even before 2015 too
• State of Jigsaw (March 8 2015)
• http://openjdk.java.net/projects/jigsaw/spec/sotms/
• JavaOne 2016 (also Devoxx BE 2017)
• http://openjdk.java.net/projects/jigsaw/talks/#j1-2016
• Code was integrated in JDK9 EA build 111
• See also: http://blog.codefx.org/java/dev/features-project-jigsaw-java-9/
• http://blog.codefx.org/java/dev/javaone-2015-under-the-hood-of-project-jigsaw/
66