Java 9,10 e… 11
Rodrigo Cândido da Silva
@rcandidosilva
Java SE Timeline
• [1994] JDK Alpha e Beta
• [1996] JDK 1.0 (8 pacotes!)
• [1996] JDK 1.1
• [1998] Java 2 (J2SE 1.2)
• [2000] J2SE 1.3
• [2002] J2SE 1.4
• [2005] J2SE 5.0
• [2006] Java SE 6
• [2011] Java SE 7
• [2014] Java SE 8
•[2017] Java SE 9
•[3/2018] Java SE 10 (18.3)
•[9/2018] Java SE 11 (18.3)
Java
9
Java 9 Features
• (JEP 200) The Modular JDK
• (JEP 102) Process API Updates
• (JEP 110) HTTP 2 Client
• (JEP 222) jshell: The Java Shell
• (JEP 225) HTML5 Javadoc
• (JEP 226) UTF-8 Property Files
• (JEP 227) Unicode 7.0
• (JEP 269) Factory Methods for Collections
• (JEP 282) jlink: The Java Linker
• (JEP 238) Multi-Release JAR Files
• (JEP 241) Remove the hat Tool
• (JEP 248) Make G1 the Default Garbage Collector
• (JEP 251) Multi-Resolution Images
• (JEP 288) Disable SHA-1 Certificates
http://openjdk.java.net/projects/jdk9/
• (JEP 213) Milling Project Coin
• (JEP 259) Stack-Walking API
• (JEP 217) Annotations Pipeline 2.0
• (JEP 236) Parser API for Nashorn
• (JEP 158) Unified JVM logging
• (JEP 285) Spins-Wait Hints
• (JEP 268) XML Catalog API
• (JEP 277) Enhanced Deprecation
• (JEP 280) Indify String Concatenation
• (JEP 287) SHA-3 Hash Algorithms
• (JEP 295) Ahead-of-Time Compilation
• (JEP 262) TIFF Image I/O
• (JEP 254) Compact Strings
• (JEP 292) Implement Selected ECMAScript 6 in Nashorn
Modularidade (Jigsaw)
• Torna Java SE mais escalável e flexível
- IoT, Microservices
• Minimiza classpath hell
• Java standard classes foram modularizadas
- rt.jar tem agora 94 módulos definidos
• Possui alguns problemas de incompatibilidade com legado
- Mas pode ser desligado durante a execução
Modularidade (Jigsaw)
Java SE 9 Modules
JDK/JRE File Structure
Modularidade (Jigsaw)
Modularidade (Jigsaw)
Java SE 8 Java SE 9
• Estrutura das aplicações
Modularidade (Jigsaw)
JLink
• Ferramenta para geração de uma JVM minimizada
JDeps
• Ferramenta fundamental para migração para módulos
Multi-Release Jar Files
• JAR pode conter versões diferentes de classes e resources
• MANIFEST.MF contém Multi-Release: true
• Subdiretório /META-INF/versions contém um diretório com
número da versão
Collection Factories
• Novos métodos adicionados para criação de coleções imutáveis
-List, Set, Map
List immutableList = List.of();
List immutableList = List.of("one","two","three");
Map emptyImmutableMap = Map.of()
Map nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three")
Private Interface Methods
• Possibilidade implementar métodos privados em interfaces
interface InterfaceWithPrivateMethods {
private static String staticPrivate() {
return "static private";
}
private String instancePrivate() {
return "instance private";
}
default void check() {
String result = staticPrivate();
(new InterfaceWithPrivateMethods() {}).pvt.instancePrivate();
}
}
Diamond Operator Extension
• Pode ser utilizado agora em conjunto com classes anônimas
FooClass<Integer> fc = new FooClass<>(1) { // anonymous inner class
};
FooClass<? extends Integer> fc0 = new FooClass<>(1) {
// anonymous inner class
};
FooClass<?> fc1 = new FooClass<>(1) { // anonymous inner class
};
Reactive Streams
• Suporte à programação reativa
- http://reactivestreams.org
• Interface Flow com suporte à publish-
subscribe
- Publisher, Subscriber,
Processor, Subscription
Process API
• Melhorias na API para controlar e gerenciar processos do
sistema operacional
ProcessHandle self = ProcessHandle.current();
long PID = self.getPid();
ProcessHandle.Info procInfo = self.info();
Optional<String[]> args = procInfo.arguments();
Optional<String> cmd = procInfo.commandLine();
Optional<Instant> startTime = procInfo.startInstant();
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
HTTP/2
• Suporta conexões persistentes, cabeçalhos mais eficientes
dentre outra melhorias
• Nova API adicionada: java.net.http
- Substitui a antiga implementação HttpURLConnection
URI httpURI = new URI("http://localhost:8080");
HttpRequest request = HttpRequest.create(httpURI).GET();
HttpResponse response = request.response();
String responseBody = response.body(HttpResponse.asString());
JShell
• REPL (Read-Eval-Print-Loop)
• Novo comando adicionado no JDK: jshell
Try-With-Resources
• Não é mais necessário utilizar uma variável para ser gerenciada
pela estrutura
MyAutoCloseable mac = new MyAutoCloseable();
try (mac) {
// do some stuff with mac
}
try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) {
// do some stuff with finalCloseable
} catch (Exception ex) { }
Enhanced Deprecation
• @Deprecated anotação suporta agora
- since - String que define a partir de quando
- forRemoval - indica que será removido na próxima versão
- jdeprscan - JDK tool para deprecation scan
- Applet API is deprecated now
$ jdeprscan --class-path classes example.Deprecations
class example/Deprecations uses type java/rmi/RMISecurityManager deprecated
class example/Deprecations uses method javax/swing/JList getSelectedValues()
deprecated
Stream Enhacements
• dropWhile() / takeWhile()
• Improved iterate
• Parallel Files.lines()
• Stream from Optional
Javadoc Improvements
• Formato compatível com HTML5 markup
• Suporte a definição dos módulos (Jigsaw)
• Adicionado um novo mecanismo de consulta
Unicode 7.0/8.0
• Unicode 7: 2.834 new characters
• Unicode 8: 7.716 new characters
• Suporte à UTF-8 nos property files
string
.replaceAll("🚗 ", "value")
.replaceAll("🚫 ", “nextValue")
Security Enhancements
• Melhoria performance GHASH e RSA
• Suporte para SHA-3 hash algorithm
• TLS application-layer protocol negotiation
• OCSP Stapling for TLS
• PKCS12 key stores by default (replaced JKS)
• Disabled SHA-1 certificate
G1 Garbage Collector
• G1 é o coletor padrão agora
• Multithreaded; com pausas
mais curtas e previsíveis
• Compacta o heap, reduzindo a
fragmentação
G1-GC
Parallel GC
Java
10
Java 10 Features
• (JEP 286) Local-Variable Type Inference
• (JEP 296) Consolidate the JDK Forest into a Single Repository
• (JEP 304) Garbage-Collector Interface
• (JEP 307) Parallel Full GC for G1
• (JEP 310) Application Class-Data Sharing
• (JEP 312) Thread-Local Handshakes
• (JEP 313) Remove the Native-Header Generation Tool (javah)
• (JEP 314) Additional Unicode Language-Tag Extensions
• (JEP 316) Heap Allocation on Alternative Memory Devices
• (JEP 317) Experimental Java-Based JIT Compiler
• (JEP 319) Root Certificates
• (JEP 322) Time-Based Release Versioning
http://openjdk.java.net/projects/jdk/10/
Local-Variable Type Inference
• Inferência automática de tipos para variáveis locais
var list = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream(); // infers Stream<String>
for (var item: list) {
// Indexes in the enhanced for-loop
}
for (var i; i < 10; i++) {
// Locals declared in a traditional for-loop
}
Local-Variable Type Inference
• !!!CUIDADO!!! Existem restrições para utilização
public int someMethod(var a, var b) {} // DOES NOT WORK - Method parameters
private var getFoo() { // DOES NOT WORK - Method return types
return "foo";
}
class SomeClass {
var someString = "Hello"; // DOES NOT WORK - Field class level
SomeClass(var someString) {} // DOES NOT WORK - Constructor parameters
}
var compareString = String::compareTo // DOES NOT WORK - Lambda expressions
try {} catch (var exception) {} // DOES NOT WORK - Try/catch expressions
Collection APIs Improvements
• Pequenas melhorias na API de coleções
List<T> newCopy = List.copyOf(anotherList);
Set<T> newCopy = Set.copyOf(anotherSet);
Map<T> newCopy = Map.copyOf(anotherMap);
List<Integer> result = Arrays.asList(1, 2, 3, 4).stream()
.collect(Collectors.toUnmodifiableList());
Set<Integer> set = IntStream.range(1, 5, 6, 7).boxed()
.collect(Collectors.toUnmodifiableSet());
Map<Integer, Double> map = IntStream.range(1, 5).boxed()
.collect(Collectors.toUnmodifiableMap(i -> i, i -> Math.pow(i, 3)));
Docker Runtime Support
Application Class-Data Sharing (CDS)
• Ajuda a reduzir consideravelmente o startup time e memory
footprint da aplicação
java -Xshare:off -XX:+UseAppCDS -XX:DumpLoadedClassList=hello.lst 
-cp hello.jar HelloWorld
java -Xshare:dump -XX:+UseAppCDS -XX:SharedClassListFile=hello.lst 
-XX:SharedArchiveFile=hello.jsa -cp hello.jar
java -Xshare:dump -XX:+UseAppCDS -XX:SharedClassListFile=hello.lst 
-XX:SharedArchiveFile=hello.jsa -cp hello.jar
Retorna a lista de classes para compartilhamento (hello.lst)
Cria o arquivo de compartilhamento para ser utilizado pelo CDS (hello.jsa)
Utiliza o arquivo de compartilhamento no startup da aplicação
Java
11
Java 11 Features
• (JEP 309) Dynamic Class-File Constants
• (JEP 318) Epsilon: A No-Op Garbage Collector
• (JEP 320) Remove the Java EE and CORBA Modules
• (JEP 321) HTTP Client (Standard)
• (JEP 323) Local-Variable Syntax for Lambda Parameters
• (JEP 324) Key Agreement with Curve22519 and Curve448
• (JEP 327) Unicode 10
• (JEP 328) Flight Recorder
• (JEP 329) ChaCha20 and Poly1305 Crypto Algorithms
• (JEP 330) Launch Single-File Source-Code Programs
http://openjdk.java.net/projects/jdk/11/
Perguntas
?
Obrigado !
@rcandidosilva

Java 9, 10 e ... 11

  • 1.
    Java 9,10 e…11 Rodrigo Cândido da Silva @rcandidosilva
  • 3.
    Java SE Timeline •[1994] JDK Alpha e Beta • [1996] JDK 1.0 (8 pacotes!) • [1996] JDK 1.1 • [1998] Java 2 (J2SE 1.2) • [2000] J2SE 1.3 • [2002] J2SE 1.4 • [2005] J2SE 5.0 • [2006] Java SE 6 • [2011] Java SE 7 • [2014] Java SE 8 •[2017] Java SE 9 •[3/2018] Java SE 10 (18.3) •[9/2018] Java SE 11 (18.3)
  • 4.
  • 5.
    Java 9 Features •(JEP 200) The Modular JDK • (JEP 102) Process API Updates • (JEP 110) HTTP 2 Client • (JEP 222) jshell: The Java Shell • (JEP 225) HTML5 Javadoc • (JEP 226) UTF-8 Property Files • (JEP 227) Unicode 7.0 • (JEP 269) Factory Methods for Collections • (JEP 282) jlink: The Java Linker • (JEP 238) Multi-Release JAR Files • (JEP 241) Remove the hat Tool • (JEP 248) Make G1 the Default Garbage Collector • (JEP 251) Multi-Resolution Images • (JEP 288) Disable SHA-1 Certificates http://openjdk.java.net/projects/jdk9/ • (JEP 213) Milling Project Coin • (JEP 259) Stack-Walking API • (JEP 217) Annotations Pipeline 2.0 • (JEP 236) Parser API for Nashorn • (JEP 158) Unified JVM logging • (JEP 285) Spins-Wait Hints • (JEP 268) XML Catalog API • (JEP 277) Enhanced Deprecation • (JEP 280) Indify String Concatenation • (JEP 287) SHA-3 Hash Algorithms • (JEP 295) Ahead-of-Time Compilation • (JEP 262) TIFF Image I/O • (JEP 254) Compact Strings • (JEP 292) Implement Selected ECMAScript 6 in Nashorn
  • 6.
    Modularidade (Jigsaw) • TornaJava SE mais escalável e flexível - IoT, Microservices • Minimiza classpath hell • Java standard classes foram modularizadas - rt.jar tem agora 94 módulos definidos • Possui alguns problemas de incompatibilidade com legado - Mas pode ser desligado durante a execução
  • 7.
  • 8.
    Java SE 9Modules
  • 9.
  • 10.
  • 11.
    Modularidade (Jigsaw) Java SE8 Java SE 9 • Estrutura das aplicações
  • 12.
  • 13.
    JLink • Ferramenta parageração de uma JVM minimizada
  • 14.
    JDeps • Ferramenta fundamentalpara migração para módulos
  • 15.
    Multi-Release Jar Files •JAR pode conter versões diferentes de classes e resources • MANIFEST.MF contém Multi-Release: true • Subdiretório /META-INF/versions contém um diretório com número da versão
  • 16.
    Collection Factories • Novosmétodos adicionados para criação de coleções imutáveis -List, Set, Map List immutableList = List.of(); List immutableList = List.of("one","two","three"); Map emptyImmutableMap = Map.of() Map nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three")
  • 17.
    Private Interface Methods •Possibilidade implementar métodos privados em interfaces interface InterfaceWithPrivateMethods { private static String staticPrivate() { return "static private"; } private String instancePrivate() { return "instance private"; } default void check() { String result = staticPrivate(); (new InterfaceWithPrivateMethods() {}).pvt.instancePrivate(); } }
  • 18.
    Diamond Operator Extension •Pode ser utilizado agora em conjunto com classes anônimas FooClass<Integer> fc = new FooClass<>(1) { // anonymous inner class }; FooClass<? extends Integer> fc0 = new FooClass<>(1) { // anonymous inner class }; FooClass<?> fc1 = new FooClass<>(1) { // anonymous inner class };
  • 19.
    Reactive Streams • Suporteà programação reativa - http://reactivestreams.org • Interface Flow com suporte à publish- subscribe - Publisher, Subscriber, Processor, Subscription
  • 20.
    Process API • Melhoriasna API para controlar e gerenciar processos do sistema operacional ProcessHandle self = ProcessHandle.current(); long PID = self.getPid(); ProcessHandle.Info procInfo = self.info(); Optional<String[]> args = procInfo.arguments(); Optional<String> cmd = procInfo.commandLine(); Optional<Instant> startTime = procInfo.startInstant(); Optional<Duration> cpuUsage = procInfo.totalCpuDuration();
  • 21.
    HTTP/2 • Suporta conexõespersistentes, cabeçalhos mais eficientes dentre outra melhorias • Nova API adicionada: java.net.http - Substitui a antiga implementação HttpURLConnection URI httpURI = new URI("http://localhost:8080"); HttpRequest request = HttpRequest.create(httpURI).GET(); HttpResponse response = request.response(); String responseBody = response.body(HttpResponse.asString());
  • 22.
    JShell • REPL (Read-Eval-Print-Loop) •Novo comando adicionado no JDK: jshell
  • 23.
    Try-With-Resources • Não émais necessário utilizar uma variável para ser gerenciada pela estrutura MyAutoCloseable mac = new MyAutoCloseable(); try (mac) { // do some stuff with mac } try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) { // do some stuff with finalCloseable } catch (Exception ex) { }
  • 24.
    Enhanced Deprecation • @Deprecatedanotação suporta agora - since - String que define a partir de quando - forRemoval - indica que será removido na próxima versão - jdeprscan - JDK tool para deprecation scan - Applet API is deprecated now $ jdeprscan --class-path classes example.Deprecations class example/Deprecations uses type java/rmi/RMISecurityManager deprecated class example/Deprecations uses method javax/swing/JList getSelectedValues() deprecated
  • 25.
    Stream Enhacements • dropWhile()/ takeWhile() • Improved iterate • Parallel Files.lines() • Stream from Optional
  • 26.
    Javadoc Improvements • Formatocompatível com HTML5 markup • Suporte a definição dos módulos (Jigsaw) • Adicionado um novo mecanismo de consulta
  • 27.
    Unicode 7.0/8.0 • Unicode7: 2.834 new characters • Unicode 8: 7.716 new characters • Suporte à UTF-8 nos property files string .replaceAll("🚗 ", "value") .replaceAll("🚫 ", “nextValue")
  • 28.
    Security Enhancements • Melhoriaperformance GHASH e RSA • Suporte para SHA-3 hash algorithm • TLS application-layer protocol negotiation • OCSP Stapling for TLS • PKCS12 key stores by default (replaced JKS) • Disabled SHA-1 certificate
  • 29.
    G1 Garbage Collector •G1 é o coletor padrão agora • Multithreaded; com pausas mais curtas e previsíveis • Compacta o heap, reduzindo a fragmentação G1-GC Parallel GC
  • 30.
  • 31.
    Java 10 Features •(JEP 286) Local-Variable Type Inference • (JEP 296) Consolidate the JDK Forest into a Single Repository • (JEP 304) Garbage-Collector Interface • (JEP 307) Parallel Full GC for G1 • (JEP 310) Application Class-Data Sharing • (JEP 312) Thread-Local Handshakes • (JEP 313) Remove the Native-Header Generation Tool (javah) • (JEP 314) Additional Unicode Language-Tag Extensions • (JEP 316) Heap Allocation on Alternative Memory Devices • (JEP 317) Experimental Java-Based JIT Compiler • (JEP 319) Root Certificates • (JEP 322) Time-Based Release Versioning http://openjdk.java.net/projects/jdk/10/
  • 32.
    Local-Variable Type Inference •Inferência automática de tipos para variáveis locais var list = new ArrayList<String>(); // infers ArrayList<String> var stream = list.stream(); // infers Stream<String> for (var item: list) { // Indexes in the enhanced for-loop } for (var i; i < 10; i++) { // Locals declared in a traditional for-loop }
  • 33.
    Local-Variable Type Inference •!!!CUIDADO!!! Existem restrições para utilização public int someMethod(var a, var b) {} // DOES NOT WORK - Method parameters private var getFoo() { // DOES NOT WORK - Method return types return "foo"; } class SomeClass { var someString = "Hello"; // DOES NOT WORK - Field class level SomeClass(var someString) {} // DOES NOT WORK - Constructor parameters } var compareString = String::compareTo // DOES NOT WORK - Lambda expressions try {} catch (var exception) {} // DOES NOT WORK - Try/catch expressions
  • 34.
    Collection APIs Improvements •Pequenas melhorias na API de coleções List<T> newCopy = List.copyOf(anotherList); Set<T> newCopy = Set.copyOf(anotherSet); Map<T> newCopy = Map.copyOf(anotherMap); List<Integer> result = Arrays.asList(1, 2, 3, 4).stream() .collect(Collectors.toUnmodifiableList()); Set<Integer> set = IntStream.range(1, 5, 6, 7).boxed() .collect(Collectors.toUnmodifiableSet()); Map<Integer, Double> map = IntStream.range(1, 5).boxed() .collect(Collectors.toUnmodifiableMap(i -> i, i -> Math.pow(i, 3)));
  • 35.
  • 36.
    Application Class-Data Sharing(CDS) • Ajuda a reduzir consideravelmente o startup time e memory footprint da aplicação java -Xshare:off -XX:+UseAppCDS -XX:DumpLoadedClassList=hello.lst -cp hello.jar HelloWorld java -Xshare:dump -XX:+UseAppCDS -XX:SharedClassListFile=hello.lst -XX:SharedArchiveFile=hello.jsa -cp hello.jar java -Xshare:dump -XX:+UseAppCDS -XX:SharedClassListFile=hello.lst -XX:SharedArchiveFile=hello.jsa -cp hello.jar Retorna a lista de classes para compartilhamento (hello.lst) Cria o arquivo de compartilhamento para ser utilizado pelo CDS (hello.jsa) Utiliza o arquivo de compartilhamento no startup da aplicação
  • 37.
  • 38.
    Java 11 Features •(JEP 309) Dynamic Class-File Constants • (JEP 318) Epsilon: A No-Op Garbage Collector • (JEP 320) Remove the Java EE and CORBA Modules • (JEP 321) HTTP Client (Standard) • (JEP 323) Local-Variable Syntax for Lambda Parameters • (JEP 324) Key Agreement with Curve22519 and Curve448 • (JEP 327) Unicode 10 • (JEP 328) Flight Recorder • (JEP 329) ChaCha20 and Poly1305 Crypto Algorithms • (JEP 330) Launch Single-File Source-Code Programs http://openjdk.java.net/projects/jdk/11/
  • 39.
  • 40.