4. IBM Java 9
IBM Java 9 beta is open for business
SDK are rewritten to use the new Java module system
Join IBM Open Beta Program
https://developer.ibm.com/javasdk/2017/02/08/our-java-9-beta-is-open-for-business/
5. Main Features of Java 9
JDK
Module System (JPMS)
Versioning Schema
Tools
+Multi-Release JAR Files
+Compile for Older Versions
+jshell +jlink +jmod
-hprof -jhat
~javac ~java ~jcmd
Security
-SHA-1
+SHA-3
6. Main Features of Java 9
Deployment
Deprecate Java Plugin (Applet)
jlink
Language
@SafeVargs
Try-with-resources
Diamond w/ anonymous classes
Identifier name Underscore (_) removal
Private interface methods.
Javadoc
HTML5 output
Javadoc search
Module System support
7. Main Features of Java 9
Core Libraries
Process API Updates
Variable Handles
Compact Strings
Platform Logging API and Service
More Concurrency Updates
Factory Methods for Collections
Enhanced Method Handles
Enhanced Deprecation
Spin-Wait Hints
Filter Incoming Serialization Data
Stack-Walking API
8. Main Features of Java 9
JVM
Compiler control
Segmented Code Cache (for native code)
JVM Tuning
Unified JVM/GC Logging
Remove GC Combinations Deprecated in JDK 8
Make G1 the Default Garbage Collector
Deprecate the CMS GC
Internationalization
Unicode 8.0
UTF-8 properties
Installer
9. Main Features of Java 9
Client
TIFF Image I/O
Multi-Resolution Images
JavaFX module system support
BeanInfo annotations
HiDPI Graphics on Windows and Linux
Platform-Specific Desktop Features
Nashorn (JS Engine)
Parser API for Nashorn
Implement Selected ECMAScript 6 Features in Nashorn
− Template strings
− let, const, and block scope
− Iterators and for..of loops
− Map, Set, WeakMap, and WeakSet
− Symbols
− Binary and octal literals
10. JPMS – Module System
GOALS
Make the Java SE Platform/JDK, more easily
scalable down to small computing devices
Improve the security and maintainability of
Java SE Platform Implementations in general,
and the JDK in particular;
Enable improved application performance
Make it easier for developers to construct and
maintain libraries and large applications,
for both the Java SE and EE Platforms.
11. JPMS – Module System
THUS
Strong encapsulation (among modules)
Better architectural design
Improve security
Reliable configuration
Introduce dependency management (sort of)
Space efficiency & performance
Run on small devices (IoT)
Compile-Run time errors reduce.
12. JPMS – Module Definition
A module is a named, self-describing collection of code and data.
And contains packages (classes&interfaces),
resources, other static information (e.g. META-INF)
module modul.demo.a {} // depends on java.base
module modul.demo.bank {
exports modul.demo.bank;
}
module modul.demo.bank.client {
requires modul.demo.bank;
}
14. JPMS – Platform Modules
Java Platform is divided into modules.
https://blog.codecentric.de/files/2015/11/jdk-tr1.png
15. JPMS – Platform Modules
Base Module (“java.base”)
Always present
Only module known by module system
Exports all of the platform's core packages
Every other module depends implicitly upon base module
Base module depends upon no other module
module java.base {
exports java.io;
exports java.lang;
exports java.lang.invoke;
exports java.lang.module;
exports java.lang.ref;
exports java.lang.reflect;
exports java.net;
...
}
16. JPMS – Using Modules
Module Path
Means to locate whole modules (similar to classpath)
Resolves module dependences
System path contains module artifacts (jars) or
module directories
e.g. %JAVA_HOME%/jmods;libs
If the module system cannot find a dependent module
or if it encounters two modules w/ same name
then the compiler or virtual machine report an error and exits
18. JPMS – Implied Readibility
// Application Code
Driver d = DriverManager.getDriver(url); java.sql→
Connection c = d.connect(url, props); java.sql→
d.getParentLogger().info("Connection acquired"); java.logging→
How can the application access “java.logging” module?
Revise “java.sql” module descriptor
module java.sql {
requires public java.logging;
requires public java.xml;
exports java.sql;
exports javax.sql;
exports javax.transaction.xa;
}
If one module exports a package containing a type whose signature refers to a package
in a second module then the declaration of the first module should include a requires
public dependence upon the second.
19. JPMS – Unnamed Module
All jars loaded from the classpath are considered
as a member of Unnamed Module.
Ensures that every type is associated with a module.
The unnamed module reads every other module
(i.e. all named & built-in platform modules)
Thus existing Java 8 application compile and run on Java 9.
(unless api's are deprecated or removed)
The unnamed module exports all of its packages.
But named module can not access types in the unnamed module.
If a package is defined in both a named module and the unnamed
module then the package in the unnamed module is ignored.
20. JPMS – Unnamed Module
If our application is written before Java 8, module dependences
in Java 9 is as below:
Grey covered jars are in classpath, therefore they are defined
as “unnamed module”.
21. JPMS – Bottom-Up Migration
What to migrate to Java 9?
Find the intermodule dependencies (using jdep)
Use buttom-up approach to select&migrate to modules.
com-foo-app.jar
com-foo-bar.jar
org-baz-qux.jar
It is easy to migrate “org.baz.qux” to module system.
Because it has no dependences.
22. JPMS – Bottom-Up Migration
Continue to bottom-up migration
What if “org.baz.qux.jar” is maintained by another organization and
cannot be converted to a named module?
Is it possible to migrate other jars into modules?
23. JPMS – Automatic Module
A jar w/o module descriptor in modulepath is defined as
automatic module
Accesses all other modules
Implicitly exports all of its packages Unnamed Module
thus can be depend upon by Named Modules
Mudule name is automatically determined using jar name
(subject to change)
Removes the file extension
Removes trailing version number
replaces all the non-alphanumeric characters with dots
mysql-connector-java-6.1.6.jar → mysql.connector.java
24. JPMS – Top-Down Migration
− Application jars are not module.
− JRE is Java9. Therefore, platform (java.*) modules exists
in environment.
− Want to convert application jars into modules.
Only com-foo-app.jar and com-foo-bar.jar can be converted
org-baz-qux.jar is maintained by another organization.
com-foo-app.jar
com-foo-bar.jar
org-baz-qux.jar
Current Situation
25. JPMS – Top-Down Migration
module com.foo.bar {
requires
org.baz.qux;
}
module com.foo.app {
requires
com.foo.bar;
requires java.sql;
}
Move org-baz-qux.jar to module-path. It will have
automodule name: org-baz-qux.jar → org.baz.qux
Now com-foo-app.jar and com-foo-bar.jar can
depend upon org.baz.qux module.
26. JPMS – Top-Down Migration
Notes
Automatic Modules allow an existing application to be migrated
to modules from the top down (first app.jar then other jars)
To migrate the jars in classpath
Find and analyze interdependency (jdeps)
Convert the source code of your organization into modules
Move 3rd
party jars into module-path to make them automodule
thus, your module code may depend/read the automodules.
(until module versions of 3rd
party jars are prepared)
27. JPMS – Module Types Summary
MODULE TYPE MODULE DESCRIPTOR LOCATION
Application Module Exists Module-path
Automatic Module Doesn't exist Module-path
Unnamed Module Exists or Doesn't exist Class-path
Platform Module Exists Platform's Module-path
MODULE TYPE EXPORTS
PACKAGES
CAN READ
MODULES
CAN BE READ BY
MODULES
Application Module Explicitly Application
Platform
Automatic
Application
Automatic
Unnamed
Platform Module Explicitly Platform All types of modules
Unnamed Module All All types of modules Application
Automatic
Unnamed
Automatic Module All All types of modules Application
Automatic
Unnamed
29. JPMS – ServiceLoader
Provides loose-coupling among modules.
Based on the java.util.ServiceLoader mechanism.
Service Loader locates the service providers at run-time
by searching jars in classpath.
Automatic modules (old jars) may also provide services by
placing the service class into META-INF/services.
Service File: META-INF/services/com.example.CodecSet
File Content: com.example.impl.StandardCodecs # Standard codecs
Iterator<CodecSet> codecs =
ServiceLoader.load(CodecSet.class).iterator();
foreach(codec) {
//select codec instance.
}
31. JPMS – Services
Highligts
Declaring service relation is module declaration
Improves efficiency and clarity (locating/loading time)
Provides compile&run time accessibility check
Provides compile-time type compatibility check
Provides capability to run Ahead-of-Time Compilation
Provides safe linking prior to run-time
32. JPMS – Reflection
package java.lang.reflect;
public final class Module {
public String getName();
public ModuleDescriptor getDescriptor();
public ClassLoader getClassLoader();
public boolean canRead(Module target);
public boolean isExported(String packageName);
}
Every Class object has an associated Module object
Module object returns by the Class::getModule method
ModuleDescriptor class represents module descriptor
canRead() tells whether the module can read the target module
isExported() tells whether the module exports given package
Class.forName() continues to work as soon as the reflected class
is exported in target module and readable by caller module.
33. JPMS – Class Loader
Modules names/packages don't have to interfere with each other
A module has to be loaded/associated by only one class loader
Exception: Unnamed Module is associated by all class loaders.
Existing Hierarchy is
preserved.
Bootstrap and extension
class loaders load platform
modules
Application class loader
loads classes of modules in
the module path.
Can load classes from one or
more modules
34.
Besides application modules, new layer may contain upgradable
platform modules as soon as they are loaded from a different location.
During resolution process, modules in new layer can read modules in
lower layers.
CONTAINER
JPMS – Layers
Upgradeable modules
v1.0v1.1
Container launches the
application w/ initial layer (L1)
An upgrade necessitates and
v1.1 modules are loaded in a
new layer (L2) on the top of
initial layer (L1) from a
different jar location.
Container performs this loading
operation by using module
reflection API's and dynamic
class loading.
35. JPMS – Qualified Exports
Allows a package to be exported to specifically-named modules.
module java.base {
...
exports sun.reflect to
java.corba,
java.logging,
java.sql,
java.sql.rowset,
jdk.scripting.nashorn;
}
Can be used to hide the internal implementation from the
unintended users.
Provides a kind of module security. (e.g. in container environment)
37. Build Tools – Javac
https://docs.oracle.com/javase/9/tools/javac.htm
IN WINDOWS
> javac --module-path ..mods -d ..modsmodul.demo.bank.client
srcmodul.demo.bank.clientmodule-info.java
srcmodul.demo.bank.clientmoduldemobankclientBankClient.java
javac [ options ] [ sourcefiles ]
Option Description
--module-path Where the dependent modules are located.
-d Destination folder to generate class files.
IN UNIX
$ javac --module-path ..mods -d ..modsmodul.demo.bank.client
$(find src -name "*.java")
38. Build Tools – Jar
https://docs.oracle.com/javase/9/tools/jar.htm
> jar -c -f libsmodul.demo.bank.client-2.0.jar --main-
class=modul.demo.bank.client.BankClient --module-version=2.0 -C
modul.demo.bank.client .
jar [OPTION...] [ [--release VERSION] [-C dir] files] ...
Option Description
-c Create jar.
-f Location and name of the generated jar file.
--main-class Main class of the jar which is placed in manifest.
--module-version Version of the modul (informative).
-C <dir> <files> Changes the directory to <dir> and includes the <files> in there.
Main Operation Modes
--create --update --extract --list --print-module-
descriptor
39. Build Tools – Jar (multi release)
jar9 --create –file out-sample/sample.jar -C out-sample/out8 .
--release 9 -C out-sample/out9 .
Single jar may differentiate wrt java versions it's running.
That is, a jar may contain different versions of classes for
different java versions.
JAR FILE CONTENT
└ com
└ sample
├ Main.class
└ Sample.class
└ META-INF
└ versions
└ 9
└ com
└ sample
└ Sample.class
40. Build Tools – JLink
jlink [options] --module-path modulepath --add-modules mods --output path
> jlink --module-path "%JAVA_HOME%/jmods;libs" --add-modules
modul.demo.bank,modul.demo.bank.client,modul.demo.bank.impl --compress=2
--output bankapp2 --launcher
startBankClient=modul.demo.bank.client/modul.demo.bank.client.BankClient
Used to assemble (and optimize) modules and their
dependencies into a custom runtime image(?).
Custom Runtime Image: An distribution of our application that
contains only necessary application and java runtime modules,
other application files, optionally start script, etc.
Simplifies and reduces the size of deployment.
https://docs.oracle.com/javase/9/tools/jlink.htm
45. Build Tools – Jmod
https://docs.oracle.com/javase/9/tools/jdeps.htm
jmod (create|extract|list|describe|hash) [options] jmod-file
> jmod create --module-path "%JAVA_HOME%jmods";. --class-path
modul.demo.bank.client --module-version 1.2
jmodfilesmodul.demo.bank.client.jmod
File format that aggregates not only .class files but also
metadata, and other resource files.
Intented to kill jar format.
Allows to transport files, not to execute. That is, it can be used
during compile and link-time, but not at run-time.
Jmod is actually zip format. Zip tool can be used to manage.
Platform modules are distributed in jmod format.
46. Build Tools – Jmod
https://docs.oracle.com/javase/9/tools/jdeps.htm
c:Workworkspace_oxygenmods>jmod list modul.demo.bank
Error: mode must be one of create, extract, list, describe, or hash: list
Usage: jmod (create|extract|list|describe|hash) <OPTIONS> <jmod-file>
use --help for a list of possible options
There are still bugs in tools. Use with cautions.
47. Build Tools – Jimage
Is a container format for storing (and indexing) modules,
classes and resources in the JDK.
Aims to replaces rt.jar, resources.jar, tools.jar and other jars in
JDK and JRE.
Used to create binary runtime images.
Intended to be internal to JDK.
Can be created by jlink tool. (<generated-app>libmodules)
Jimage tool can be used to print information about and extract
necessary files from jimage file.
48. Build Tools – Jimage
>jimage info bankapplibmodules
Major Version: 1
Minor Version: 0
Flags: 0
Resource Count: 6155
Table Length: 6155
Offsets Size: 24620
Redirects Size: 24620
Locations Size: 131167
Strings Size: 135107
Index Size: 315542
jimage <extract | info | list | verify> <options> jimage...
>jimage list bankapplibmodules
Module: java.base
...
Module: modul.demo.bank.client
...
Module: modul.demo.bank.impl
...
Module: modul.demo.bank
META-INF/MANIFEST.MF
modul/demo/bank/IAccount.class
modul/demo/bank/IAccountProvider.class
module-info.class
49. Build Tools – Jdeprscan
https://docs.oracle.com/javase/9/tools/jdeprscan.htm
>jdeprscan --class-path libs*.jar libsmodul.demo.bank.client@2.0.jar
Jar file libsmodul.demo.bank.impl@2.0.jar:
error: cannot find class modul/demo/bank/IAccount
error: cannot find class modul/demo/bank/IAccountProvider
Jar file libsmodul.demo.bank@2.0.jar:
Jar file libsmodul.demo.bank.client@2.0.jar:
Scans files for usage of deprecated API elements.
jdeprscan [ options ]{dir|jar|class}
>jdeprscan Resource.class
class deneme/Resource uses deprecated method java/lang/Thread::stop()V
50. Diag Tools – Jcmd
Send diagnostic command requests to the JVM.
Used to control Java Flight Recordings, troubleshoot, and
diagnose JVM and Java Applications.
jcmd <process id/main class> VM.version
jcmd <process id/main class> VM.system_properties
jcmd <process id/main class> VM.uptime
jcmd <process id/main class> GC.class_histogram
jcmd <process id/main class> GC.heap_dump filename=Myheapdump
// jmap -dump:file=<file> <pid>→
jcmd <process id/main class> Thread.print
// kill -3
jcmd <process id/main class> PerfCounter.print
// prints all performance counters in the process
51. Diag Tools –
Native Memory Tracking
Tracks internal memory usage for a Java HotSpot VM.
5-10% JVM performance drop and memory usage.
2 commands are available
-XX:NativeMemoryTracking=summary
-XX:NativeMemoryTracking=detail
Create a baseline: jcmd <pid> VM.native_memory baseline
Monitor memory change: jcmd <pid> VM.native_memory detail.diff
53. Diag Tools –
Java Mission Control
JDK profiling and diagnostics tools platform for HotSpot JVM.
Provides basic monitoring, managing, and production time
profiling and diagnostics with high performance.
JMC uses Java Flight Recording (JFR) outcome and JFR is a
commercial feature in production, not in dev/test/preprod.
JFR records the java application and runtime w/ little overhead.
Overhead is depend on the selected triggers before recording.
JMC displays the detailed profiling data about Memory, Cpu,
Code, Threads, I/O, System, Events.
>jcmd 7060 JFR.start name=MyRecording settings=profile delay=20s
duration=2m filename=C:TEMPmyrecording.jfr
>jcmd 7060 JFR.check
>jcmd 7060 JFR.stop
>jcmd 7060 JFR.dump name=MyRecording filename=C:TEMPmyrecording.jfr
55. Diag Tools – JConsole
JMX compliant monitoring tool.
Monitor Memory, Threads, Classes, VM summary, other Mbeans.
56. Diag Tools – Jdb
The command-line debugger which uses Java Debug Interface
(JDI).
JDK ships with several Serviceability Agent (SA) connectors to
attach to a crash dump or hung process in a local or remote
host.
SACoreAttachingConnector
SADebugServerAttachingConnector
SAPIDAttachingConnector
These connectors are used by IDEs. (e.g. Eclipse)
// Attach to running process
jdb -connect sun.jvm.hotspot.jdi.SAPIDAttachingConnector:pid=9302
> threads
...
> thread 0x7
...
57. Diag Tools – Jinfo
Use jcmd instead of old jinfo utility.
Gets configuration, system properties, command-line flags
information from a running Java process or core file.
>jinfo 16172
Java System Properties:
#Mon Jul 31 11:00:27 EET 2017
awt.toolkit=sun.awt.windows.WToolkit
file.encoding.pkg=sun.io
java.specification.version=9
...
VM Flags:
-XX:CICompilerCount=1 -XX:CodeCacheExpansionSize=32768
...
VM Arguments:
jvm_args:
-agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:64982
-Dfile.encoding=Cp1254
java_command: deneme.Resource
...
58. Diag Tools – Jmap
Use jcmd or JMC/JFR instead of old jmap utility.
Displays memory-related statistics for a running VM or core file.
Jmap Samples
>jmap -heap 29620
>jmap -histo 29620
>jmap -histo /solaris-sparcv9/bin/java core
// the exact java executable is needed to parse core file.
>jmap -permstat 29620
59. Diag Tools – Jps
Displays the running Java processes for current user on the host
machine.
Jps Samples
>jps
10196 Jps
6292
16172 Resource
>jps -ml
6292
9300 jdk.jcmd/sun.tools.jps.Jps -ml
16172 deneme.Resource
60. Diag Tools – Jstack
Use jcmd instead of old jstack utility.
Displays the stack traces of all threads of the virtual machine.
Can attach to the specified process or core file.
Can perform deadlock detection.
Can be obtained programmatically: Thread.getAllStackTraces
Mixed Stack: Native Stack + Java Stack
Jstack Samples
>jstack 16172
2017-07-31 11:32:01
Full thread dump Java HotSpot(TM) Server VM (9+178 mixed mode, emulated-
client):
...
"Service Thread" #12 daemon prio=9 os_prio=0 tid=0x05125400 nid=0x3fa8
runnable [0x00000000]
java.lang.Thread.State: RUNNABLE
...
63. try-with-resources
// A final resource
final Resource resource1 = new Resource("resource1");
// An effectively final resource
Resource resource2 = new Resource("resource2");
// IN JAVA 7/8
try (Resource r1 = resource1; Resource r2 = resource2) {
// Use of resource1 and resource 2 through r1 and r2.
}
// JAVA 9
try (resource1; resource2) {
// Use of resource1 and resource 2.
}
64. @SafeVarargs
public static void faultyMethod(List<String>... l) {
Object[] objectArray = l; // Valid
objectArray[0] = Arrays.asList(42);
String s = l[0].get(0); // ClassCastException
}
faultyMethod(Arrays.asList("Hello!"),
Arrays.asList("World!"));
Type Erasure translates List<String>... List[] Object[]→ →
If your method handles varargs properly, use @SafeVarargs
Can be used in static and non-constructor method (non-private)
Private methods are added in Java 9.
65. Diamond w/ anonymous classes
MyHandler<Integer> intHandler = new MyHandler<>(1) {
public void handle() {
// handling code...
}
};
Java 9 allows diamond(<>) in annonymous classes.
67. Core Library Changes -
Process API
ProcessHandle and Info classes are added to API to interact
conveniently w/ processes (and trees).
ProcessHandle handle = ProcessHandle.current();
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
Stream<ProcessHandle> stream = ProcessHandle.allProcesses();
interface ProcessHandle {
long pid();
Optional<ProcessHandle> parent();
Stream<ProcessHandle> children();
Stream<ProcessHandle> descendants();
CompletableFuture<ProcessHandle>
onExit();
boolean supportsNormalTermination();
boolean destroy();
boolean destroyForcibly();
boolean isAlive();
Info info();
}
interface Info {
public Optional<Duration>
totalCpuDuration();
public Optional<String> command();
public Optional<String> commandLine();
public Optional<String[]> arguments();
public Optional<Instant> startInstant();
public Optional<String> user();
}
68. Core Library Changes -
Variable Handles
Completely copied and pasted :-)
Excerpt from JEP 193
“As concurrent and parallel programming in Java continue to expand,
programmers are increasingly frustrated by not being able to use Java
constructs to arrange atomic or ordered operations on the fields of
individual classes; for example, atomically incrementing a count field.”
The existing possibilities to do this are all lacking in some sense or the
other:
Atomic... classes add “both space overhead and additional concurrency
issues to manage indirection”
FieldUpdaters often lead to “more overhead than the operation itself”
Unsafe is, well, unsafe – it’s neither standardized nor supported and slated
to become inaccessible in Java 10.
“A variable handle is a typed reference to a variable, which supports read
and write access to the variable under a variety of access modes.
Supported variable kinds include instance fields, static fields and array
69. Core Library Changes -
Variable Handles
Define a standard means to invoke the equivalents of various
java.util.concurrent.atomic and sun.misc.Unsafe operations upon object
fields and array elements, a standard set of fence operations for fine-
grained control of memory ordering, and a standard reachability-fence
operation to ensure that a referenced object remains strongly reachable.
public class AtomicBoolean implements java.io.Serializable {
private static final VarHandle VALUE;
static {
try {
MethodHandles.Lookup l = MethodHandles.lookup();
VALUE = l.findVarHandle(AtomicBoolean.class, "value", int.class);
} catch (ReflectiveOperationException e) {
throw new Error(e);
}}
private volatile int value;
public final boolean compareAndSet(boolean expectedValue, boolean newValue) {
return VALUE.compareAndSet(this,
(expectedValue ? 1 : 0),
(newValue ? 1 : 0));
}
70. Core Library Changes -
Compact Strings
20%-30% of an average application's live data is char[] inside String
objects.
char = 2 bytes for UTF-16 representation.
But, for most of the strings ISO-8859-1, which is 1 byte, is sufficient.
Compress the data as byte[], if all characters are ISO-8859-1 encoded.
In average java application, memory consumption reduces by 10%-15%
and causes less time for GC.
Disabled if necessary: XX:-CompactStrings
71. Core Library Changes -
Platform Logging API &
Service
Defines a minimal logging API (java.util.logging) and service interface
(System.Logger) which platform classes can use to log messages.
Application can provide its own logging API (e.g. LogBack) to the
platform via ServiceLoader, thus, platform and the application can use
the same logging API.
If no logging API is provided, default platform logger (java.util.logging) is
used.
72. Core Library Changes -
Concurrency Updates
Publish-subscriber feature of Reactive Stream is supported by
Concurrency API using Flow class.
CompletableFuture API enhencements.
Other small concurrency enhencements & documentation/javadoc
updates.
73. Core Library Changes -
Reactive Streams
Flow.Publisher: Publishes item to the subscribers. Subscriber
should Publisher.subscribe() in order to receive requests.
Flow.Subscriber: Subscribes to Publisher and consume request
from it via onNext(T), onError(Exception), onComplete()
Flow.Subscription: Link between Publisher and Subscriber.
request(n) method is called to start messaging.
Subscriber.onNext(T) method is called at most n times or fewer if
cancel() is called or application is terminated.
74. Core Library Changes -
Completable Future
Future class is introduced to Java in 1.5 to ease async processing.
But it doesn't have a mechanism to combine computation or handle
errors.
In Java 8, CompletableFuture is added to handle composing,
combining, executing steps, and handling error in async computation.
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(1000);
completableFuture.complete("completed");
return null;
});
Executors.newCachedThreadPool().submit(() -> {
Thread.sleep(500);
completableFuture.cancel(false);
return null;
});
76. Core Library Changes -
Factory Methods for Collections
New factory methods are added to List, Set, and Map interfaces.
Only immutable instances are created.
List<String> list = List.of("a", "b", "c");
Set<String> set = Set.of("a", "b", "c");
Map<String, Integer> mapImmediate = Map.of(
"one", 1,
"two", 2,
"three", 3);
Map<String, Integer> mapEntries = Map.ofEntries(
entry("one", 1),
entry("two", 2),
entry("three", 3));
77. Core Library Changes -
Enhanced Deprecation
2 new elements are added to @Deprecated annotation
@Deprecated(forRemoval=true): API will be release in the next
release.
@Deprecated(since="version"): Deprecated since the depicted
version.
Jdeprscan can be used to find deprecated API elements.
@Deprecated(forRemoval=true, since="9")
private void method() {
// old algorithm
}
78. Core Library Changes -
Spin-Wait Hints
Used to (busy) wait the caller on a condition.
Busy-wait implemented by Thread.onSpinWait() method.
Some OS/processor architectures may optimize the spin-wait
operations.
This method is just a hint. It doesn't guaranties to optimize spin-wait.
class EventHandler {
volatile boolean eventNotificationNotReceived;
void waitForEventAndHandleIt() {
while ( eventNotificationNotReceived ) {
java.lang.Thread.onSpinWait();
}
readAndProcessEvent();
}
void readAndProcessEvent() {
// Read event from some source and process it
}
}
79. Core Library Changes -
Stack-Walking API
Provides easy filtering and lazy access to stack trace information.
Functionality is provided by java.lang.StackWalker class.
Short walk and long walk on stack trace can be stopped by the given
criteria. Thus, the cost of examining all stack trace is avoided.
List<StackFrame> frames =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
.walk((s) -> s.collect(Collectors.toList()));
System.out.println("All frames : n" + frames.toString());
List<StackFrame> frames = StackWalker.getInstance().walk(s ->
s.dropWhile(f -> f.getClassName().startsWith("com.foo."))
.limit(10)
.collect(Collectors.toList()));
System.out.println("Ten frames : n" + frames.toString());
80. JVM Tuning - GC Changes
GC combinations - deprecated in Java8 / removed in Java9:
DefNew + CMS
ParNew + SerialOld
Incremental CMS
G1 has better overall performance than throughput collector. Thus G1
became default collector.
CMS GC is deprecated. When -XX:+UseConcMarkSweepGC option is
used, a warning message is displayed.
The "foreground" mode for CMS has also been removed.
The following command line flags have been removed:
-Xincgc -XX:+UseCMSCompactAtFullCollection
-XX:+CMSIncrementalMode -XX:+CMSFullGCsBeforeCompaction
-XX:+UseCMSCollectionPassing
-XX:+UseParNewGC flag has been deprecated and will likely be
removed in a future release.
81. Highlights
91 JEP is implemented in Java 9.
JPMS (Jigsaw) is main feature of Java 9.
Planned to release more frequently (2 year period).
http://openjdk.java.net/projects/jdk10/
http://openjdk.java.net/projects/valhalla/