Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java 9 language and core API updates

Java 9 language and core API updates

1bc80e2eee2adeaa8bb577798d92e9d0?s=128

Anton Arhipov

April 19, 2017
Tweet

Transcript

  1. JAVA 9 LANGUAGE & CORE API UPDATES @ANTONARHIPOV

  2. JAVA 9 SCHEDULE •16th March 2017 Rampdown Phase 2 •6th

    July 2017 Final Release Candidate •27th July 2017 General Availability
  3. THINGS I CAN’T TALK ABOUT YET Detailed performance metrics Experience

    based analysis
  4. http://openjdk.java.net/projects/jdk9/

  5. AGENDA • JEP-213: Milling project coin • JEP-102: Process API

    updates • JEP-266: More concurrency updates • JEP-269: Convenience factory methods for collections • JEP-277: Enhanced deprecation • JEP-259: Stack-Walking API
  6. AGENDA • Date & Time API enhancements • Stream/Optional API

    enhancements • JShell
  7. JSR 376: JAVA PLATFORM MODULE SYSTEM

  8. • http://openjdk.java.net/projects/jigsaw/ • JEP 200: The Modular JDK • JEP

    220: Modular Run-Time Images • JEP 260: Encapsulate Most Internal APIs • JEP 261: Module System • JEP 282: jlink: The Java Linker JSR 376: JAVA PLATFORM MODULE SYSTEM
  9. None
  10. None
  11. DIAMOND <> OPERATOR WITH ANONYMOUS INNER CLASSES

  12. DIAMOND <> OPERATOR WITH ANONYMOUS INNER CLASSES List<String> strings =

    new ArrayList<String>(){{ add("a"); add("b"); add("c"); }}; Java 8
  13. DIAMOND <> OPERATOR WITH ANONYMOUS INNER CLASSES List<String> strings =

    new ArrayList<String>(){{ add("a"); add("b"); add("c"); }}; Java 8 List<String> strings = new ArrayList<>(){{ add("a"); add("b"); add("c"); }}; Java 9
  14. ENHANCED TRY-WITH-RESOURCES

  15. ENHANCED TRY-WITH-RESOURCES try (BufferedReader reader = Files.newBufferedReader(…)) { //… }

    Java 8
  16. ENHANCED TRY-WITH-RESOURCES try (BufferedReader reader = Files.newBufferedReader(…)) { //… }

    Java 8 BufferedReader reader = Files.newBufferedReader(…); try (BufferedReader reader1 = reader) { //… }
  17. ENHANCED TRY-WITH-RESOURCES Java 9 BufferedReader reader = Files.newBufferedReader(…); try (reader)

    { //… } try (BufferedReader reader = Files.newBufferedReader(…)) { //… } Java 8 BufferedReader reader = Files.newBufferedReader(…); try (BufferedReader reader1 = reader) { //… }
  18. int _ = 1; UNDERSCORE _ IS NOT ALLOWED AS

    AN IDENTIFIER NAME
  19. int _ = 1; UNDERSCORE _ IS NOT ALLOWED AS

    AN IDENTIFIER NAME Java 8: warning: '_' used as an identifier int _ = 1; ^ (use of '_' as an identifier might not be supported in releases after Java SE 8)
  20. int _ = 1; UNDERSCORE _ IS NOT ALLOWED AS

    AN IDENTIFIER NAME Java 9: error: as of release 9, '_' is a keyword, and may not be used as an identifier int _ = 1; ^
  21. public class UnderscoreDemo { public static void main(String[] __) {

    for (int ___ = 0; ___ < __.length; ___++) System.out.println(__[___]); } } UNDERSCORE _ IS NOT ALLOWED AS AN IDENTIFIER NAME
  22. UNDERSCORE _ IS NOT ALLOWED AS AN IDENTIFIER NAME JEP-302:

    Lambda leftovers (Java 10?) BiFunction<Integer, String, String> biss = (i, _) -> String.valueOf(i);
  23. UNDERSCORE _ IS NOT ALLOWED AS AN IDENTIFIER NAME JEP-302:

    Lambda leftovers (Java 10?) BiFunction<Integer, String, String> biss = (i, _) -> String.valueOf(i);
  24. PRIVATE METHODS IN INTERFACES interface SomeInterface { default void methodA()

    {} private void methodB() {} private static void methodC(){} private default methodD(){} } // since Java 8 // new in Java 9 // new in Java 9 // error: cannot be // private and default
  25. @SAFEVARARGS ON PRIVATE METHODS List<String> list1 = singletonList("Hi"); List<String> list2

    = singletonList("Hi"); call(list1, list2); static void call(List<String>... lists) { String s = lists[0].get(0); System.out.println(s); }
  26. @SAFEVARARGS ON PRIVATE METHODS List<String> list1 = singletonList("Hi"); List<String> list2

    = singletonList("Hi"); call(list1, list2); static void call(List<String>... lists) { String s = lists[0].get(0); System.out.println(s); } warning: [unchecked] Possible heap pollution from parameterized vararg type List<String>: static void call(List<String>... lists) { warning: [unchecked] unchecked generic array creation for varargs parameter of type List<String>[]: call(myList1, myList2);
  27. @SAFEVARARGS ON PRIVATE METHODS List<String> list1 = singletonList("Hi"); List<String> list2

    = singletonList("Hi"); call(list1, list2); @SafeVarargs static void call(List<String>... lists) { String s = lists[0].get(0); System.out.println(s); }
  28. @SAFEVARARGS ON PRIVATE METHODS List<String> list1 = singletonList("Hi"); List<String> list2

    = singletonList("Hi"); call(list1, list2); @SafeVarargs private void call(List<String>... lists) { String s = lists[0].get(0); System.out.println(s); } error: Invalid SafeVarargs annotation. Instance method call(List<String>...) is not final. private void call(List<String>... stringLists) { ^ Java 8:
  29. @SAFEVARARGS ON PRIVATE METHODS List<String> list1 = singletonList("Hi"); List<String> list2

    = singletonList("Hi"); call(list1, list2); @SafeVarargs private void call(List<String>... lists) { String s = lists[0].get(0); System.out.println(s); } Java 9: O.K.
  30. CORE THE

  31. PROCESS API UPDATES

  32. PROCESS API UPDATES RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); String name =

    runtimeMXBean.getName(); String pid = name.split("@")[0]; Java 8:
  33. PROCESS API UPDATES RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); String name =

    runtimeMXBean.getName(); String pid = name.split("@")[0]; Java 8: long pid = ProcessHandle.current().getPid(); Java 9:
  34. PROCESS API UPDATES RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); String name =

    runtimeMXBean.getName(); String pid = name.split("@")[0]; Java 8: long pid = ProcessHandle.current().getPid(); Java 9: Stream<ProcessHandle> handles = ProcessHandle.allProcesses();
  35. https://github.com/zeroturnaround/zt-exec ZT PROCESS EXECUTOR new ProcessExecutor() .command("java", "-version") .redirectOutput(Slf4jStream.of("MyProcess").asInfo()) .execute();

  36. KILL ‘EM ALL! void cleanupApplication(String applicationName) { ProcessHandle .allProcesses() .filter(process

    -> isApplication(applicationName, process)) .forEach(process -> process.info().command().ifPresent(command -> closeAndLog(process, command))); } void closeAndLog(ProcessHandle process, String command) { String status = process.destroyForcibly() ? " Success!" : " Failed"; System.out.println("Killing ... " + command + status); } boolean isApplication(final String appName, final ProcessHandle process) { return process.info().command().filter(command -> command.contains(appName)).isPresent(); }
  37. https://github.com/zeroturnaround/zt-process-killer ZT PROCESS KILLER int pid = Integer.parseInt( FileUtils.readFileToString( new

    File("pidfile"))); PidProcess process = Processes.newPidProcess(pid); ProcessUtil.destroyGracefullyOrForcefullyAndWait(process, 30, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
  38. MORE CONCURRENCY UPDATES

  39. FACTORY METHODS FOR COLLECTIONS Set.of("a", "b", "c"); List.of("a", "b", "c");

    Map.of(1, "val1", 2, "val2", 3, "val3");
  40. FACTORY METHODS FOR COLLECTIONS Set<String> set = new HashSet<>(); set.add("a");

    set.add("b"); set.add("c"); set = Collections.unmodifiableSet(set);
  41. FACTORY METHODS FOR COLLECTIONS Set<String> set = new HashSet<>(); set.add("a");

    set.add("b"); set.add("c"); set = Collections.unmodifiableSet(set); Set<String> set = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("a", "b", "c")));
  42. FACTORY METHODS FOR COLLECTIONS Set<String> set = new HashSet<>(); set.add("a");

    set.add("b"); set.add("c"); set = Collections.unmodifiableSet(set); Set<String> set = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("a", "b", "c"))); Set<String> set = Collections.unmodifiableSet( Stream.of("a", "b", "c").collect(toSet()));
  43. FACTORY METHODS FOR COLLECTIONS Set<String> set = new HashSet<>(); set.add("a");

    set.add("b"); set.add("c"); set = Collections.unmodifiableSet(set); Set<String> set = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("a", "b", "c"))); Set<String> set = Collections.unmodifiableSet( Stream.of("a", "b", "c").collect(toSet())); Set<String> set = Set.of("a", "b", "c");
  44. @Deprecated

  45. @Deprecated(since="9", forRemoval=true)

  46. @Deprecated(since="9", forRemoval=true) Still no description or info

  47. None
  48. None
  49. STACK-WALKING API StackWalker VS Thread::getStackTrace • Filter / asset /

    skip certain frames • Get the instance of declaring class itself • Get either a short stack trace or complete stack trace
  50. STACK-WALKING API StackWalker walker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE); List<StackWalker.StackFrame> stack = walker.walk(

    s -> s.collect(Collectors.toList()) );
  51. STACK-WALKING API StackWalker walker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE); List<StackWalker.StackFrame> stack = walker.walk(

    s -> s.collect(Collectors.toList()) ); List<StackWalker.StackFrame> stack = walker.walk( s -> s.filter(f -> interestingClasses.contains( f.getDeclaringClass())).findFirst() );
  52. DATE & TIME API IMPROVEMENTS

  53. DATE & TIME API IMPROVEMENTS LocalDate now = LocalDate.now(); //

    2017-04-20 LocalDate java9release = LocalDate.of(2017, Month.JULY, 27); now.datesUntil(java9release); JDK-8146218 - Add LocalDate.datesUntil method producing Stream
  54. DATE & TIME API IMPROVEMENTS now.datesUntil(java9release, Period.ofDays(3)); LocalDate now =

    LocalDate.now(); // 2017-04-20 LocalDate java9release = LocalDate.of(2017, Month.JULY, 27); now.datesUntil(java9release); JDK-8146218 - Add LocalDate.datesUntil method producing Stream
  55. DATE & TIME API IMPROVEMENTS JDK-8146218 - Add LocalDate.datesUntil method

    producing Stream LocalDate now = LocalDate.now(); // 2017-04-20 LocalDate java9release = LocalDate.of(2017, Month.JULY, 27); now.datesUntil(java9release); now.datesUntil(java9release, Period.ofDays(3)) .forEach(out::println);
  56. DATE & TIME API IMPROVEMENTS JDK-8146218 - Add LocalDate.datesUntil method

    producing Stream LocalDate now = LocalDate.now(); // 2017-04-20 LocalDate java9release = LocalDate.of(2017, Month.JULY, 27); now.datesUntil(java9release); now.datesUntil(java9release, Period.ofDays(3)) .forEach(out::println); 2017-04-20 2017-04-23 2017-04-26 2017-05-29 …
  57. DATE & TIME API IMPROVEMENTS JDK-8142936 - Duration methods for

    days, hours, minutes, seconds, etc. Duration#toDaysPart() Duration#toHoursPart() Duration#toMinutesPart() Duration#toSecondsPart() Duration#toMillisPart() Duration#toNanosPart()
  58. DATE & TIME API IMPROVEMENTS JDK-8142936 - Duration methods for

    days, hours, minutes, seconds, etc. Duration.ofMinutes(15000).toDaysPart(); // 10
  59. DATE & TIME API IMPROVEMENTS JDK-8142936 - Duration methods for

    days, hours, minutes, seconds, etc. Duration.ofMinutes(15000).toDaysPart(); // 10 JDK-8148849 - Truncating Duration. Duration.ofMinutes(15000).truncatedTo(ChronoUnit.DAYS); // 10
  60. DATE & TIME API IMPROVEMENTS JDK-8142936 - Duration methods for

    days, hours, minutes, seconds, etc. Duration.ofMinutes(15000).toDaysPart(); // 10 JDK-8148849 - Truncating Duration. Duration.ofMinutes(15000).truncatedTo(ChronoUnit.DAYS); // 10 JDK-8032510 - Add Duration.dividedBy(Duration) Duration.ofDays(10).dividedBy(Duration.ofMinutes(1000)); // 14
  61. STREAM/OPTIONAL API ENHANCEMENTS

  62. OPTIONAL#GET

  63. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated?

  64. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated? Optional<String> optional = getData(); if (optional.isPresent()) {

    doSomething(optional.get()); } else { doSomethingElse(); }
  65. OPTIONAL#GET

  66. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated?

  67. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated? Optional<String> optional = getData(); if (optional.isPresent()) {

    doSomething(optional.get()); } else { doSomethingElse(); }
  68. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated? Optional<String> optional = getData(); if (optional.isPresent()) {

    doSomething(optional.get()); } else { doSomethingElse(); } optional.ifPresentOrElse( this::doSomething, this::doSomethingElse );
  69. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated?

  70. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated? streamOfOptionals.filter(Optional::isPresent).map(Optional::get);

  71. OPTIONAL#GET http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-April/040484.html Deprecated? streamOfOptionals.filter(Optional::isPresent).map(Optional::get); streamOfOptionals.flatMap(Optional::stream);

  72. OPTIONAL#OR

  73. OPTIONAL#OR Optional<User> user = findUserById(42) .or(() -> findUserByName("Anton"));

  74. OPTIONAL#OFNULLABLE

  75. OPTIONAL#OFNULLABLE Stream.of("Anton", "Cas", "Ethan") .flatMap(n -> Stream.ofNullable(findUserByName(n))) .collect(Collectors.toList());

  76. STREAM#TAKEWHILE & #DROPWHILE

  77. Stream.of(1, 2, 3, 4, 5, 1, 2) .takeWhile(i -> i

    < 3) .forEach(out::println); STREAM#TAKEWHILE & #DROPWHILE
  78. Stream.of(1, 2, 3, 4, 5, 1, 2) .takeWhile(i -> i

    < 3) .forEach(out::println); 1 2 STREAM#TAKEWHILE & #DROPWHILE
  79. Stream.of(1, 2, 3, 4, 5, 1, 2) .takeWhile(i -> i

    < 3) .forEach(out::println); Stream.of(1, 2, 3, 4, 5, 1, 2) .dropWhile(i -> i < 3) .forEach(out::println); 1 2 STREAM#TAKEWHILE & #DROPWHILE
  80. Stream.of(1, 2, 3, 4, 5, 1, 2) .takeWhile(i -> i

    < 3) .forEach(out::println); Stream.of(1, 2, 3, 4, 5, 1, 2) .dropWhile(i -> i < 3) .forEach(out::println); 1 2 3 4 5 1 2 STREAM#TAKEWHILE & #DROPWHILE
  81. STREAM#ITERATE

  82. STREAM#ITERATE Stream.iterate(1, i -> i <= 16, i -> 2

    * i) .forEach(out::println);
  83. 1 2 4 8 16 STREAM#ITERATE Stream.iterate(1, i -> i

    <= 16, i -> 2 * i) .forEach(out::println);
  84. STREAM#ITERATE

  85. STREAM#ITERATE Stream.iterate(2L, n -> n + 1)

  86. STREAM#ITERATE Stream.iterate(2L, n -> n + 1) .filter(n -> n

    % 2 == 0)
  87. STREAM#ITERATE Stream.iterate(2L, n -> n + 1) .filter(n -> n

    % 2 == 0) .skip(1000) .limit(3) .forEach(System.out::println);
  88. 2002 2004 2006 STREAM#ITERATE Stream.iterate(2L, n -> n + 1)

    .filter(n -> n % 2 == 0) .skip(1000) .limit(3) .forEach(System.out::println);
  89. None