SlideShare a Scribd company logo
Java 9
That's one small step for a man, one giant leap for mankind.
Neil Amstrong
The New Module System
and
Other Features
Agenda

History

Main Features

JPMS Demo

Jshell Demo
Oracle Java History

JDK 1.0 (January 23, 1996)

JDK 1.1 (February 19, 1997)

J2SE 1.2 (December 8, 1998)

J2SE 1.3 (May 8, 2000)

J2SE 1.4 (February 6, 2002)

J2SE 5.0 (September 30, 2004)

Java SE 6 (December 11, 2006)

Java SE 7 (July 28, 2011)

Java SE 8 (March 18, 2014)

Java 9 (September 21, 2017) (planned)
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/
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
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
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
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
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
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.
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.
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;
}
JPMS – Module Definition
Directory Structure
ModulDemo2BankClient/ → Eclipse project base
src/ → Source folder
modul.demo.bank.client/ → module source folder
module-info.java → module descriptor
modul/demo/bank/client/ → package
BankClient.java → java Class
Jar Structure
META-INF/
META-INF/MANIFEST.MF
module-info.class
modul/demo/bank/client/BankClient.class
JPMS – Platform Modules
Java Platform is divided into modules.
https://blog.codecentric.de/files/2015/11/jdk-tr1.png
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;
...
}
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
JPMS – Module Resolution
module com.foo.bar {
requires
org.baz.qux;
}
module com.foo.app {
requires
com.foo.bar;
requires java.sql;
}
module org.baz.qux {
}
Resolution Start Here:
Initial Application Module
module java.sql {
requires java.logging;
requires java.xml;
exports java.sql;
exports javax.sql;
exports
javax.transaction.xa;
}
MODULE
GRAPH
Explicit dependence
vs
Implicit dependence
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.
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.
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”.
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.
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?
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
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
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.
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)
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
JPMS – Readability Summary
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.
}
JPMS – Services
module java.sql {
requires public java.logging;
requires public java.xml;
exports java.sql;
exports javax.sql;
exports javax.transaction.xa;
uses java.sql.Driver;
}
module com.mysql.jdbc {
requires java.sql;
requires org.slf4j;
exports com.mysql.jdbc;
provides java.sql.Driver
with com.mysql.jdbc.Driver;
}
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
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.
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

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.
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)
JJJJJJJJJJJPPPPPPPPPPPPPPPPP MMMMMMMM MMMMMMMM SSSSSSSSSSSSSSS
J:::::::::JP::::::::::::::::P M:::::::M M:::::::M SS:::::::::::::::S
J:::::::::JP::::::PPPPPP:::::P M::::::::M M::::::::MS:::::SSSSSS::::::S
JJ:::::::JJPP:::::P P:::::PM:::::::::M M:::::::::MS:::::S SSSSSSS
J:::::J P::::P P:::::PM::::::::::M M::::::::::MS:::::S
J:::::J P::::P P:::::PM:::::::::::M M:::::::::::MS:::::S
J:::::J P::::PPPPPP:::::P M:::::::M::::M M::::M:::::::M S::::SSSS
J:::::j P:::::::::::::PP M::::::M M::::M M::::M M::::::M SS::::::SSSSS
J:::::J P::::PPPPPPPPP M::::::M M::::M::::M M::::::M SSS::::::::SS
JJJJJJJ J:::::J P::::P M::::::M M:::::::M M::::::M SSSSSS::::S
J:::::J J:::::J P::::P M::::::M M:::::M M::::::M S:::::S
J::::::J J::::::J P::::P M::::::M MMMMM M::::::M S:::::S
J:::::::JJJ:::::::J PP::::::PP M::::::M M::::::MSSSSSSS S:::::S
JJ:::::::::::::JJ P::::::::P M::::::M M::::::MS::::::SSSSSS:::::S
JJ:::::::::JJ P::::::::P M::::::M M::::::MS:::::::::::::::SS
JJJJJJJJJ PPPPPPPPPP MMMMMMMM MMMMMMMM SSSSSSSSSSSSSSS
DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEMMMMMMMM MMMMMMMM OOOOOOOOO
D::::::::::::DDD E::::::::::::::::::::EM:::::::M M:::::::M OO:::::::::OO
D:::::::::::::::DD E::::::::::::::::::::EM::::::::M M::::::::M OO:::::::::::::OO
DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EM:::::::::M M:::::::::MO:::::::OOO:::::::O
D:::::D D:::::D E:::::E EEEEEEM::::::::::M M::::::::::MO::::::O O::::::O
D:::::D D:::::DE:::::E M:::::::::::M M:::::::::::MO:::::O O:::::O
D:::::D D:::::DE::::::EEEEEEEEEE M:::::::M::::M M::::M:::::::MO:::::O O:::::O
D:::::D D:::::DE:::::::::::::::E M::::::M M::::M M::::M M::::::MO:::::O O:::::O
D:::::D D:::::DE:::::::::::::::E M::::::M M::::M::::M M::::::MO:::::O O:::::O
D:::::D D:::::DE::::::EEEEEEEEEE M::::::M M:::::::M M::::::MO:::::O O:::::O
D:::::D D:::::DE:::::E M::::::M M:::::M M::::::MO:::::O O:::::O
D:::::D D:::::D E:::::E EEEEEEM::::::M MMMMM M::::::MO::::::O O::::::O
DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EM::::::M M::::::MO:::::::OOO:::::::O
D:::::::::::::::DD E::::::::::::::::::::EM::::::M M::::::M OO:::::::::::::OO
D::::::::::::DDD E::::::::::::::::::::EM::::::M M::::::M OO:::::::::OO
DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEMMMMMMMM MMMMMMMM OOOOOOOOO
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")
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
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
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
Build Tools – JLink
├───bin
│ │ java.dll
│ │ java.exe
│ │ javaw.exe
│ │ jimage.dll
│ │ keytool.exe
│ │ net.dll
│ │ nio.dll
│ │ startBankClient
│ │ startBankClient.bat
│ │ zip.dll
├───conf
│ │ net.properties
│ └───security
│ └───policy
...
├───include
│ │ jni.h
│ └───win32
│ jni_md.h
├───legal
│ └───java.base
│ aes.md
├───lib
│ │ jvm.cfg
│ │ jvm.lib
│ │ modules
│ ├───security
│ └───server
└─── release
Build Tools – Java
https://docs.oracle.com/javase/9/tools/java.htm
> cd bankappbin
> java --list-modules
> java -m modul.demo.bank.client
> java -m modul.demo.bank.client/modul.demo.bank.client.BankClient
java [options] -p modulepath -m modulename[/mainclass] [args...]
CONTENT OF START SCRIPT
@echo off
set JLINK_VM_OPTIONS=
set DIR=%~dp0
"%DIR%java" %JLINK_VM_OPTIONS% -m
modul.demo.bank.client/modul.demo.bank.client.BankClient %*
Build Tools – Jdeps
https://docs.oracle.com/javase/9/tools/jdeps.htm
jdeps [options] classes ...
> jdeps -dotoutput dot --module-path . modul.demo.bank.client-2.0.jar
modul.demo.bank.impl-2.0.jar modul.demo.bank@2.0.jar
Generated files: modul.demo.bank.client.dot modul.demo.bank.dot
modul.demo.bank.impl.dot summary.dot
Content of summary.dot:
digraph "summary" {
"modul.demo.bank.client" -> "java.base (java.base)";
"modul.demo.bank.client" -> "modul.demo.bank";
"modul.demo.bank" -> "java.base (java.base)";
"modul.demo.bank.impl" -> "java.base (java.base)";
"modul.demo.bank.impl" -> "modul.demo.bank";
}
Shows the package-level or class-level dependencies of Java
class files.
Build Tools – Jdep
http://www.webgraphviz.com/
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.
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.
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.
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
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
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
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
Diag Tools –
Native Memory Tracking
Total: reserved=664192KB, committed=253120KB
- Java Heap (reserved=516096KB, committed=204800KB)
(mmap: reserved=516096KB, committed=204800KB)
- Class (reserved=6568KB, committed=4140KB)
(classes #665)
(malloc=424KB, #1000)
(mmap: reserved=6144KB, committed=3716KB)
- Thread (reserved=6868KB, committed=6868KB)
(thread #15)
(stack: reserved=6780KB, committed=6780KB)
(malloc=27KB, #66)
(arena=61KB, #30)
- Code (reserved=102414KB, committed=6314KB)
(malloc=2574KB, #74316)
(mmap: reserved=99840KB, committed=3740KB)
...
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
Diag Tools –
Java Mission Control
Diag Tools – JConsole

JMX compliant monitoring tool.

Monitor Memory, Threads, Classes, VM summary, other Mbeans.
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
...
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
...
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
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
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
...
1111111 000000000 MMMMMMMM MMMMMMMM
1::::::1 00:::::::::00 M:::::::M M:::::::M
1:::::::1 00:::::::::::::00 M::::::::M M::::::::M
111:::::1 0:::::::000:::::::0 M:::::::::M M:::::::::M
1::::1 0::::::0 0::::::0 M::::::::::M M::::::::::M
1::::1 0:::::0 0:::::0 M:::::::::::M M:::::::::::M
1::::1 0:::::0 0:::::0 M:::::::M::::M M::::M:::::::M
1::::l 0:::::0 000 0:::::0 M::::::M M::::M M::::M M::::::M
1::::l 0:::::0 000 0:::::0 M::::::M M::::M::::M M::::::M
1::::l 0:::::0 0:::::0 M::::::M M:::::::M M::::::M
1::::l 0:::::0 0:::::0 M::::::M M:::::M M::::::M
1::::l 0::::::0 0::::::0 M::::::M MMMMM M::::::M
111::::::1110:::::::000:::::::0 M::::::M M::::::M
1::::::::::1 00:::::::::::::00 M::::::M M::::::M
1::::::::::1 00:::::::::00 M::::::M M::::::M
111111111111 000000000 MMMMMMMM MMMMMMMM
BBBBBBBBBBBBBBBBB RRRRRRRRRRRRRRRRR EEEEEEEEEEEEEEEEEEEEEE AAA KKKKKKKKK KKKKKKK
B::::::::::::::::B R::::::::::::::::R E::::::::::::::::::::E A:::A K:::::::K K:::::K
B::::::BBBBBB:::::B R::::::RRRRRR:::::R E::::::::::::::::::::E A:::::A K:::::::K K:::::K
BB:::::B B:::::BRR:::::R R:::::REE::::::EEEEEEEEE::::E A:::::::A K:::::::K K::::::K
B::::B B:::::B R::::R R:::::R E:::::E EEEEEE A:::::::::A KK::::::K K:::::KKK
B::::B B:::::B R::::R R:::::R E:::::E A:::::A:::::A K:::::K K:::::K
B::::BBBBBB:::::B R::::RRRRRR:::::R E::::::EEEEEEEEEE A:::::A A:::::A K::::::K:::::K
B:::::::::::::BB R:::::::::::::RR E:::::::::::::::E A:::::A A:::::A K:::::::::::K
B::::BBBBBB:::::B R::::RRRRRR:::::R E:::::::::::::::E A:::::A A:::::A K:::::::::::K
B::::B B:::::B R::::R R:::::R E::::::EEEEEEEEEE A:::::AAAAAAAAA:::::A K::::::K:::::K
B::::B B:::::B R::::R R:::::R E:::::E A:::::::::::::::::::::A K:::::K K:::::K
B::::B B:::::B R::::R R:::::R E:::::E EEEEEE A:::::AAAAAAAAAAAAA:::::A KK::::::K K:::::KKK
BB:::::BBBBBB::::::BRR:::::R R:::::REE::::::EEEEEEEE:::::E A:::::A A:::::A K:::::::K K::::::K
B:::::::::::::::::B R::::::R R:::::RE::::::::::::::::::::E A:::::A A:::::A K:::::::K K:::::K
B::::::::::::::::B R::::::R R:::::RE::::::::::::::::::::E A:::::A A:::::A K:::::::K K:::::K
BBBBBBBBBBBBBBBBB RRRRRRRR RRRRRRREEEEEEEEEEEEEEEEEEEEEEAAAAAAA AAAAAAAKKKKKKKKK KKKKKKK
Java Language Changes

Underscore (_) is not allowed as an identifier
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.
}
@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.
Diamond w/ anonymous classes
MyHandler<Integer> intHandler = new MyHandler<>(1) {
public void handle() {
// handling code...
}
};

Java 9 allows diamond(<>) in annonymous classes.
Private interface methods

Before Java 9
public interface MyInterface {
default void init(Params params) { //logic }
default void m2(Params params) { init(params); }
default void m3() { init(null); }
}

After Java 9
public interface MyInterface {
private void init(Params params) { //logic }
default void m2(Params params) { init(params); }
default void m3() { init(null); }
}
Supported:
* public static * public abstract * public default
* private static * private
Compile error:
* private abstract * private default
See: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
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();
}
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
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));
}
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
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.
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.
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.
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;
});
Core Library Changes -
Completable Future

Java 9 additions are below:
Executor defaultExecutor()
CompletableFuture<U> newIncompleteFuture()
CompletableFuture<T> copy()
CompletionStage<T> minimalCompletionStage()
CompletableFuture<T> completeAsync(Supplier<? extends T> supplier,
Executor executor)
CompletableFuture<T> completeAsync(Supplier<? extends T> supplier)
CompletableFuture<T> orTimeout(long timeout, TimeUnit unit)
CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit
unit)
Executor delayedExecutor(long delay, TimeUnit unit, Executor executor)
Executor delayedExecutor(long delay, TimeUnit unit)
<U> CompletionStage<U> completedStage(U value)
<U> CompletionStage<U> failedStage(Throwable ex)
<U> CompletableFuture<U> failedFuture(Throwable ex)
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));
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
}
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
}
}
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());
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.
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/
Homework

How to migrate to Java 9?
TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHH HHHHHHHHH AAA NNNNNNNN NNNNNNNNKKKKKKKKK KKKKKKK
T:::::::::::::::::::::TH:::::::H H:::::::H A:::A N:::::::N N::::::NK:::::::K K:::::K
T:::::::::::::::::::::TH:::::::H H:::::::H A:::::A N::::::::N N::::::NK:::::::K K:::::K
T:::::TT:::::::TT:::::THH::::::H H::::::HH A:::::::A N:::::::::N N::::::NK:::::::K K::::::K
TTTTTT T:::::T TTTTTT H:::::H H:::::H A:::::::::A N::::::::::N N::::::NKK::::::K K:::::KKK
T:::::T H:::::H H:::::H A:::::A:::::A N:::::::::::N N::::::N K:::::K K:::::K
T:::::T H::::::HHHHH::::::H A:::::A A:::::A N:::::::N::::N N::::::N K::::::K:::::K
T:::::T H:::::::::::::::::H A:::::A A:::::A N::::::N N::::N N::::::N K:::::::::::K
T:::::T H:::::::::::::::::H A:::::A A:::::A N::::::N N::::N:::::::N K:::::::::::K
T:::::T H::::::HHHHH::::::H A:::::AAAAAAAAA:::::A N::::::N N:::::::::::N K::::::K:::::K
T:::::T H:::::H H:::::H A:::::::::::::::::::::A N::::::N N::::::::::N K:::::K K:::::K
T:::::T H:::::H H:::::H A:::::AAAAAAAAAAAAA:::::A N::::::N N:::::::::NKK::::::K K:::::KKK
TT:::::::TT HH::::::H H::::::HH A:::::A A:::::A N::::::N N::::::::NK:::::::K K::::::K
T:::::::::T H:::::::H H:::::::H A:::::A A:::::A N::::::N N:::::::NK:::::::K K:::::K
T:::::::::T H:::::::H H:::::::H A:::::A A:::::A N::::::N N::::::NK:::::::K K:::::K
TTTTTTTTTTT HHHHHHHHH HHHHHHHHHAAAAAAA AAAAAAANNNNNNNN NNNNNNNKKKKKKKKK KKKKKKK
YYYYYYY YYYYYYY OOOOOOOOO UUUUUUUU UUUUUUUU
Y:::::Y Y:::::Y OO:::::::::OO U::::::U U::::::U
Y:::::Y Y:::::Y OO:::::::::::::OO U::::::U U::::::U
Y::::::Y Y::::::YO:::::::OOO:::::::OUU:::::U U:::::UU
YYY:::::Y Y:::::YYYO::::::O O::::::O U:::::U U:::::U
Y:::::Y Y:::::Y O:::::O O:::::O U:::::D D:::::U
Y:::::Y:::::Y O:::::O O:::::O U:::::D D:::::U
Y:::::::::Y O:::::O O:::::O U:::::D D:::::U
Y:::::::Y O:::::O O:::::O U:::::D D:::::U
Y:::::Y O:::::O O:::::O U:::::D D:::::U
Y:::::Y O:::::O O:::::O U:::::D D:::::U
Y:::::Y O::::::O O::::::O U::::::U U::::::U
Y:::::Y O:::::::OOO:::::::O U:::::::UUU:::::::U
YYYY:::::YYYY OO:::::::::::::OO UU:::::::::::::UU
Y:::::::::::Y OO:::::::::OO UU:::::::::UU
YYYYYYYYYYYYY OOOOOOOOO UUUUUUUUU

More Related Content

PPT
Java 9 Module System
PPTX
Java 9: Deep Dive into Modularity and Dealing with Migration Issues
PDF
Java EE 6 : Paving The Path For The Future
PDF
Java 9 / Jigsaw - LJC / VJUG session (hackday session)
PDF
Oracle History #5
PPTX
Modularity of The Java Platform Javaday (http://javaday.org.ua/)
PDF
What's new in Java EE 6
PDF
Java EE 6 Hands-on Workshop at Dallas Tech Fest 2010
Java 9 Module System
Java 9: Deep Dive into Modularity and Dealing with Migration Issues
Java EE 6 : Paving The Path For The Future
Java 9 / Jigsaw - LJC / VJUG session (hackday session)
Oracle History #5
Modularity of The Java Platform Javaday (http://javaday.org.ua/)
What's new in Java EE 6
Java EE 6 Hands-on Workshop at Dallas Tech Fest 2010

What's hot (20)

PDF
Java EE 6 workshop at Dallas Tech Fest 2011
PDF
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
PPT
Jddk
PDF
Clusteroverview21f
PDF
Java EE6 CodeCamp16 oct 2010
PDF
Java EE 6 & GlassFish 3
PPTX
Java EE 7 for Real Enterprise Systems
PDF
JavaEE 6 and GlassFish v3 at SFJUG
PPT
Java
PDF
Java 7 workshop
PDF
Whats New In Java Ee 6
PDF
Sun Java EE 6 Overview
PDF
Java EE 6 Component Model Explained
PPTX
Java 7 and 8, what does it mean for you
PDF
The State of Java under Oracle at JCertif 2011
ODP
Java EE 6 & GlassFish v3: Paving path for the future
PDF
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
PDF
Overview of Java EE 6 by Roberto Chinnici at SFJUG
PDF
Scotas - Oracle Open World Sao Pablo
PDF
Glass Fishv3 March2010
Java EE 6 workshop at Dallas Tech Fest 2011
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Jddk
Clusteroverview21f
Java EE6 CodeCamp16 oct 2010
Java EE 6 & GlassFish 3
Java EE 7 for Real Enterprise Systems
JavaEE 6 and GlassFish v3 at SFJUG
Java
Java 7 workshop
Whats New In Java Ee 6
Sun Java EE 6 Overview
Java EE 6 Component Model Explained
Java 7 and 8, what does it mean for you
The State of Java under Oracle at JCertif 2011
Java EE 6 & GlassFish v3: Paving path for the future
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
Overview of Java EE 6 by Roberto Chinnici at SFJUG
Scotas - Oracle Open World Sao Pablo
Glass Fishv3 March2010
Ad

Similar to Java9 (20)

PDF
Java 9 / Jigsaw - AJUG/VJUG session
PDF
Modules all the way down: OSGi and the Java Platform Module System
PDF
JavaOne 2016: Life after Modularity
PPT
Java8 - Under the hood
PPTX
java basic for begginers
PPTX
What's New in Java 9
PPTX
Apache Maven supports all Java (JokerConf 2018)
PPTX
Java 9 Modularity and Project Jigsaw
PPTX
Modular Java
DOCX
Spring notes
PDF
QConSP 2018 - Java Module System
PPTX
Apache Maven supports ALL Java (Javaland 2019)
PPTX
Introduction to java
PDF
Java 9 New Features
PPTX
Java Platform Module System
PPTX
JavaScript Module Loaders
PPTX
Modularity of the Java Platform (OSGi, Jigsaw and Penrose)
PPTX
Java modulesystem
PPTX
Modern Java Workshop
PPSX
Java 9 and the impact on Maven Projects (JavaOne 2016)
Java 9 / Jigsaw - AJUG/VJUG session
Modules all the way down: OSGi and the Java Platform Module System
JavaOne 2016: Life after Modularity
Java8 - Under the hood
java basic for begginers
What's New in Java 9
Apache Maven supports all Java (JokerConf 2018)
Java 9 Modularity and Project Jigsaw
Modular Java
Spring notes
QConSP 2018 - Java Module System
Apache Maven supports ALL Java (Javaland 2019)
Introduction to java
Java 9 New Features
Java Platform Module System
JavaScript Module Loaders
Modularity of the Java Platform (OSGi, Jigsaw and Penrose)
Java modulesystem
Modern Java Workshop
Java 9 and the impact on Maven Projects (JavaOne 2016)
Ad

More from Software Infrastructure (20)

PPTX
Stream Analytics
PPTX
Quartz Scheduler
PPTX
Test Driven Development
PPTX
Deep Learning
PDF
Progressive Web Apps
PPTX
Machine learning
PPTX
PPTX
PPTX
Hazelcast sunum
PPTX
Microsoft bot framework
PPTX
Blockchain use cases
PPTX
PPTX
Server Side Swift
PPTX
Push Notification
PPTX
PDF
Big Data & Hadoop
Stream Analytics
Quartz Scheduler
Test Driven Development
Deep Learning
Progressive Web Apps
Machine learning
Hazelcast sunum
Microsoft bot framework
Blockchain use cases
Server Side Swift
Push Notification
Big Data & Hadoop

Recently uploaded (20)

PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
composite construction of structures.pdf
PPTX
Sustainable Sites - Green Building Construction
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Construction Project Organization Group 2.pptx
PPTX
Welding lecture in detail for understanding
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Well-logging-methods_new................
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
composite construction of structures.pdf
Sustainable Sites - Green Building Construction
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Foundation to blockchain - A guide to Blockchain Tech
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
UNIT 4 Total Quality Management .pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Construction Project Organization Group 2.pptx
Welding lecture in detail for understanding
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Well-logging-methods_new................

Java9

  • 1. Java 9 That's one small step for a man, one giant leap for mankind. Neil Amstrong The New Module System and Other Features
  • 3. Oracle Java History  JDK 1.0 (January 23, 1996)  JDK 1.1 (February 19, 1997)  J2SE 1.2 (December 8, 1998)  J2SE 1.3 (May 8, 2000)  J2SE 1.4 (February 6, 2002)  J2SE 5.0 (September 30, 2004)  Java SE 6 (December 11, 2006)  Java SE 7 (July 28, 2011)  Java SE 8 (March 18, 2014)  Java 9 (September 21, 2017) (planned)
  • 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; }
  • 13. JPMS – Module Definition Directory Structure ModulDemo2BankClient/ → Eclipse project base src/ → Source folder modul.demo.bank.client/ → module source folder module-info.java → module descriptor modul/demo/bank/client/ → package BankClient.java → java Class Jar Structure META-INF/ META-INF/MANIFEST.MF module-info.class modul/demo/bank/client/BankClient.class
  • 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
  • 17. JPMS – Module Resolution module com.foo.bar { requires org.baz.qux; } module com.foo.app { requires com.foo.bar; requires java.sql; } module org.baz.qux { } Resolution Start Here: Initial Application Module module java.sql { requires java.logging; requires java.xml; exports java.sql; exports javax.sql; exports javax.transaction.xa; } MODULE GRAPH Explicit dependence vs Implicit dependence
  • 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. }
  • 30. JPMS – Services module java.sql { requires public java.logging; requires public java.xml; exports java.sql; exports javax.sql; exports javax.transaction.xa; uses java.sql.Driver; } module com.mysql.jdbc { requires java.sql; requires org.slf4j; exports com.mysql.jdbc; provides java.sql.Driver with com.mysql.jdbc.Driver; }
  • 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)
  • 36. JJJJJJJJJJJPPPPPPPPPPPPPPPPP MMMMMMMM MMMMMMMM SSSSSSSSSSSSSSS J:::::::::JP::::::::::::::::P M:::::::M M:::::::M SS:::::::::::::::S J:::::::::JP::::::PPPPPP:::::P M::::::::M M::::::::MS:::::SSSSSS::::::S JJ:::::::JJPP:::::P P:::::PM:::::::::M M:::::::::MS:::::S SSSSSSS J:::::J P::::P P:::::PM::::::::::M M::::::::::MS:::::S J:::::J P::::P P:::::PM:::::::::::M M:::::::::::MS:::::S J:::::J P::::PPPPPP:::::P M:::::::M::::M M::::M:::::::M S::::SSSS J:::::j P:::::::::::::PP M::::::M M::::M M::::M M::::::M SS::::::SSSSS J:::::J P::::PPPPPPPPP M::::::M M::::M::::M M::::::M SSS::::::::SS JJJJJJJ J:::::J P::::P M::::::M M:::::::M M::::::M SSSSSS::::S J:::::J J:::::J P::::P M::::::M M:::::M M::::::M S:::::S J::::::J J::::::J P::::P M::::::M MMMMM M::::::M S:::::S J:::::::JJJ:::::::J PP::::::PP M::::::M M::::::MSSSSSSS S:::::S JJ:::::::::::::JJ P::::::::P M::::::M M::::::MS::::::SSSSSS:::::S JJ:::::::::JJ P::::::::P M::::::M M::::::MS:::::::::::::::SS JJJJJJJJJ PPPPPPPPPP MMMMMMMM MMMMMMMM SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEMMMMMMMM MMMMMMMM OOOOOOOOO D::::::::::::DDD E::::::::::::::::::::EM:::::::M M:::::::M OO:::::::::OO D:::::::::::::::DD E::::::::::::::::::::EM::::::::M M::::::::M OO:::::::::::::OO DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EM:::::::::M M:::::::::MO:::::::OOO:::::::O D:::::D D:::::D E:::::E EEEEEEM::::::::::M M::::::::::MO::::::O O::::::O D:::::D D:::::DE:::::E M:::::::::::M M:::::::::::MO:::::O O:::::O D:::::D D:::::DE::::::EEEEEEEEEE M:::::::M::::M M::::M:::::::MO:::::O O:::::O D:::::D D:::::DE:::::::::::::::E M::::::M M::::M M::::M M::::::MO:::::O O:::::O D:::::D D:::::DE:::::::::::::::E M::::::M M::::M::::M M::::::MO:::::O O:::::O D:::::D D:::::DE::::::EEEEEEEEEE M::::::M M:::::::M M::::::MO:::::O O:::::O D:::::D D:::::DE:::::E M::::::M M:::::M M::::::MO:::::O O:::::O D:::::D D:::::D E:::::E EEEEEEM::::::M MMMMM M::::::MO::::::O O::::::O DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EM::::::M M::::::MO:::::::OOO:::::::O D:::::::::::::::DD E::::::::::::::::::::EM::::::M M::::::M OO:::::::::::::OO D::::::::::::DDD E::::::::::::::::::::EM::::::M M::::::M OO:::::::::OO DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEMMMMMMMM MMMMMMMM OOOOOOOOO
  • 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
  • 41. Build Tools – JLink ├───bin │ │ java.dll │ │ java.exe │ │ javaw.exe │ │ jimage.dll │ │ keytool.exe │ │ net.dll │ │ nio.dll │ │ startBankClient │ │ startBankClient.bat │ │ zip.dll ├───conf │ │ net.properties │ └───security │ └───policy ... ├───include │ │ jni.h │ └───win32 │ jni_md.h ├───legal │ └───java.base │ aes.md ├───lib │ │ jvm.cfg │ │ jvm.lib │ │ modules │ ├───security │ └───server └─── release
  • 42. Build Tools – Java https://docs.oracle.com/javase/9/tools/java.htm > cd bankappbin > java --list-modules > java -m modul.demo.bank.client > java -m modul.demo.bank.client/modul.demo.bank.client.BankClient java [options] -p modulepath -m modulename[/mainclass] [args...] CONTENT OF START SCRIPT @echo off set JLINK_VM_OPTIONS= set DIR=%~dp0 "%DIR%java" %JLINK_VM_OPTIONS% -m modul.demo.bank.client/modul.demo.bank.client.BankClient %*
  • 43. Build Tools – Jdeps https://docs.oracle.com/javase/9/tools/jdeps.htm jdeps [options] classes ... > jdeps -dotoutput dot --module-path . modul.demo.bank.client-2.0.jar modul.demo.bank.impl-2.0.jar modul.demo.bank@2.0.jar Generated files: modul.demo.bank.client.dot modul.demo.bank.dot modul.demo.bank.impl.dot summary.dot Content of summary.dot: digraph "summary" { "modul.demo.bank.client" -> "java.base (java.base)"; "modul.demo.bank.client" -> "modul.demo.bank"; "modul.demo.bank" -> "java.base (java.base)"; "modul.demo.bank.impl" -> "java.base (java.base)"; "modul.demo.bank.impl" -> "modul.demo.bank"; } Shows the package-level or class-level dependencies of Java class files.
  • 44. Build Tools – Jdep http://www.webgraphviz.com/
  • 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
  • 52. Diag Tools – Native Memory Tracking Total: reserved=664192KB, committed=253120KB - Java Heap (reserved=516096KB, committed=204800KB) (mmap: reserved=516096KB, committed=204800KB) - Class (reserved=6568KB, committed=4140KB) (classes #665) (malloc=424KB, #1000) (mmap: reserved=6144KB, committed=3716KB) - Thread (reserved=6868KB, committed=6868KB) (thread #15) (stack: reserved=6780KB, committed=6780KB) (malloc=27KB, #66) (arena=61KB, #30) - Code (reserved=102414KB, committed=6314KB) (malloc=2574KB, #74316) (mmap: reserved=99840KB, committed=3740KB) ...
  • 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
  • 54. Diag Tools – Java Mission Control
  • 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 ...
  • 61. 1111111 000000000 MMMMMMMM MMMMMMMM 1::::::1 00:::::::::00 M:::::::M M:::::::M 1:::::::1 00:::::::::::::00 M::::::::M M::::::::M 111:::::1 0:::::::000:::::::0 M:::::::::M M:::::::::M 1::::1 0::::::0 0::::::0 M::::::::::M M::::::::::M 1::::1 0:::::0 0:::::0 M:::::::::::M M:::::::::::M 1::::1 0:::::0 0:::::0 M:::::::M::::M M::::M:::::::M 1::::l 0:::::0 000 0:::::0 M::::::M M::::M M::::M M::::::M 1::::l 0:::::0 000 0:::::0 M::::::M M::::M::::M M::::::M 1::::l 0:::::0 0:::::0 M::::::M M:::::::M M::::::M 1::::l 0:::::0 0:::::0 M::::::M M:::::M M::::::M 1::::l 0::::::0 0::::::0 M::::::M MMMMM M::::::M 111::::::1110:::::::000:::::::0 M::::::M M::::::M 1::::::::::1 00:::::::::::::00 M::::::M M::::::M 1::::::::::1 00:::::::::00 M::::::M M::::::M 111111111111 000000000 MMMMMMMM MMMMMMMM BBBBBBBBBBBBBBBBB RRRRRRRRRRRRRRRRR EEEEEEEEEEEEEEEEEEEEEE AAA KKKKKKKKK KKKKKKK B::::::::::::::::B R::::::::::::::::R E::::::::::::::::::::E A:::A K:::::::K K:::::K B::::::BBBBBB:::::B R::::::RRRRRR:::::R E::::::::::::::::::::E A:::::A K:::::::K K:::::K BB:::::B B:::::BRR:::::R R:::::REE::::::EEEEEEEEE::::E A:::::::A K:::::::K K::::::K B::::B B:::::B R::::R R:::::R E:::::E EEEEEE A:::::::::A KK::::::K K:::::KKK B::::B B:::::B R::::R R:::::R E:::::E A:::::A:::::A K:::::K K:::::K B::::BBBBBB:::::B R::::RRRRRR:::::R E::::::EEEEEEEEEE A:::::A A:::::A K::::::K:::::K B:::::::::::::BB R:::::::::::::RR E:::::::::::::::E A:::::A A:::::A K:::::::::::K B::::BBBBBB:::::B R::::RRRRRR:::::R E:::::::::::::::E A:::::A A:::::A K:::::::::::K B::::B B:::::B R::::R R:::::R E::::::EEEEEEEEEE A:::::AAAAAAAAA:::::A K::::::K:::::K B::::B B:::::B R::::R R:::::R E:::::E A:::::::::::::::::::::A K:::::K K:::::K B::::B B:::::B R::::R R:::::R E:::::E EEEEEE A:::::AAAAAAAAAAAAA:::::A KK::::::K K:::::KKK BB:::::BBBBBB::::::BRR:::::R R:::::REE::::::EEEEEEEE:::::E A:::::A A:::::A K:::::::K K::::::K B:::::::::::::::::B R::::::R R:::::RE::::::::::::::::::::E A:::::A A:::::A K:::::::K K:::::K B::::::::::::::::B R::::::R R:::::RE::::::::::::::::::::E A:::::A A:::::A K:::::::K K:::::K BBBBBBBBBBBBBBBBB RRRRRRRR RRRRRRREEEEEEEEEEEEEEEEEEEEEEAAAAAAA AAAAAAAKKKKKKKKK KKKKKKK
  • 62. Java Language Changes  Underscore (_) is not allowed as an identifier
  • 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.
  • 66. Private interface methods  Before Java 9 public interface MyInterface { default void init(Params params) { //logic } default void m2(Params params) { init(params); } default void m3() { init(null); } }  After Java 9 public interface MyInterface { private void init(Params params) { //logic } default void m2(Params params) { init(params); } default void m3() { init(null); } } Supported: * public static * public abstract * public default * private static * private Compile error: * private abstract * private default See: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
  • 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; });
  • 75. Core Library Changes - Completable Future  Java 9 additions are below: Executor defaultExecutor() CompletableFuture<U> newIncompleteFuture() CompletableFuture<T> copy() CompletionStage<T> minimalCompletionStage() CompletableFuture<T> completeAsync(Supplier<? extends T> supplier, Executor executor) CompletableFuture<T> completeAsync(Supplier<? extends T> supplier) CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit) Executor delayedExecutor(long delay, TimeUnit unit, Executor executor) Executor delayedExecutor(long delay, TimeUnit unit) <U> CompletionStage<U> completedStage(U value) <U> CompletionStage<U> failedStage(Throwable ex) <U> CompletableFuture<U> failedFuture(Throwable ex)
  • 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/
  • 83. TTTTTTTTTTTTTTTTTTTTTTTHHHHHHHHH HHHHHHHHH AAA NNNNNNNN NNNNNNNNKKKKKKKKK KKKKKKK T:::::::::::::::::::::TH:::::::H H:::::::H A:::A N:::::::N N::::::NK:::::::K K:::::K T:::::::::::::::::::::TH:::::::H H:::::::H A:::::A N::::::::N N::::::NK:::::::K K:::::K T:::::TT:::::::TT:::::THH::::::H H::::::HH A:::::::A N:::::::::N N::::::NK:::::::K K::::::K TTTTTT T:::::T TTTTTT H:::::H H:::::H A:::::::::A N::::::::::N N::::::NKK::::::K K:::::KKK T:::::T H:::::H H:::::H A:::::A:::::A N:::::::::::N N::::::N K:::::K K:::::K T:::::T H::::::HHHHH::::::H A:::::A A:::::A N:::::::N::::N N::::::N K::::::K:::::K T:::::T H:::::::::::::::::H A:::::A A:::::A N::::::N N::::N N::::::N K:::::::::::K T:::::T H:::::::::::::::::H A:::::A A:::::A N::::::N N::::N:::::::N K:::::::::::K T:::::T H::::::HHHHH::::::H A:::::AAAAAAAAA:::::A N::::::N N:::::::::::N K::::::K:::::K T:::::T H:::::H H:::::H A:::::::::::::::::::::A N::::::N N::::::::::N K:::::K K:::::K T:::::T H:::::H H:::::H A:::::AAAAAAAAAAAAA:::::A N::::::N N:::::::::NKK::::::K K:::::KKK TT:::::::TT HH::::::H H::::::HH A:::::A A:::::A N::::::N N::::::::NK:::::::K K::::::K T:::::::::T H:::::::H H:::::::H A:::::A A:::::A N::::::N N:::::::NK:::::::K K:::::K T:::::::::T H:::::::H H:::::::H A:::::A A:::::A N::::::N N::::::NK:::::::K K:::::K TTTTTTTTTTT HHHHHHHHH HHHHHHHHHAAAAAAA AAAAAAANNNNNNNN NNNNNNNKKKKKKKKK KKKKKKK YYYYYYY YYYYYYY OOOOOOOOO UUUUUUUU UUUUUUUU Y:::::Y Y:::::Y OO:::::::::OO U::::::U U::::::U Y:::::Y Y:::::Y OO:::::::::::::OO U::::::U U::::::U Y::::::Y Y::::::YO:::::::OOO:::::::OUU:::::U U:::::UU YYY:::::Y Y:::::YYYO::::::O O::::::O U:::::U U:::::U Y:::::Y Y:::::Y O:::::O O:::::O U:::::D D:::::U Y:::::Y:::::Y O:::::O O:::::O U:::::D D:::::U Y:::::::::Y O:::::O O:::::O U:::::D D:::::U Y:::::::Y O:::::O O:::::O U:::::D D:::::U Y:::::Y O:::::O O:::::O U:::::D D:::::U Y:::::Y O:::::O O:::::O U:::::D D:::::U Y:::::Y O::::::O O::::::O U::::::U U::::::U Y:::::Y O:::::::OOO:::::::O U:::::::UUU:::::::U YYYY:::::YYYY OO:::::::::::::OO UU:::::::::::::UU Y:::::::::::Y OO:::::::::OO UU:::::::::UU YYYYYYYYYYYYY OOOOOOOOO UUUUUUUUU