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

Java 14 - Updates

Java 14 - Updates

A presentation about the updates introduced in Java 14.

Switch Expressions, Pattern Matching for instanceof, Helpful NullPointerExceptions, Text Blocks, Foreign Memory Access APIs, Records and Goodbye CMS.

7363920d78e5115b7d2cf0774b60d653?s=128

Simone Bordet

May 14, 2020
Tweet

Transcript

  1. sbordet@webtide.com Java 14 - Updates @simonebordet

  2. sbordet@webtide.com Simone Bordet • @simonebordet • sbordet@webtide.com • Java Champion

    • Works @ Webtide • The company behind Jetty and CometD • JVM Tuning Expert
  3. sbordet@webtide.com Switch Expression

  4. sbordet@webtide.com Java 14 - Switch Expression • JEP 361 -

    Switch Expression ◦ After 2 previews, it’s now finalized ◦ All cases enforced by the compiler boolean workDay = switch(dayOfWeek) { case SATURDAY, SUNDAY -> false; default -> true; }
  5. sbordet@webtide.com Java 14 - Switch Expression • JEP 361 -

    Switch Expression ◦ After 2 previews, it’s now finalized ◦ All cases enforced by the compiler boolean workDay = switch(dayOfWeek) { case SATURDAY, SUNDAY -> false; default -> true; }
  6. sbordet@webtide.com Java 14 - Switch Expression • Use yield <expr>

    to return a value ◦ Not a keyword, can still be used as a variable name boolean workDay = switch (day) { case SATURDAY, SUNDAY -> { System.err.println("Weekend"); yield false; } default -> true; }
  7. sbordet@webtide.com Java 14 - Switch Expression • You can still

    use the ":" syntax: boolean workDay = switch (day) { case SATURDAY, SUNDAY: { System.err.println("Weekend"); yield false; } default: yield true; }
  8. sbordet@webtide.com Java 14 - Switch Expression • Switch expression can

    use colon or arrow syntax ◦ Cannot be mixed • Colon syntax: allows for fall-through • Arrow syntax -> NO fall-through
  9. sbordet@webtide.com Pattern Matching for instanceof

  10. sbordet@webtide.com Java 14 - Pattern Matching • JEP 305: Pattern

    Matching for instanceof boolean equals(Object obj) { if (obj instanceof MyClass that) { return this.field.equals(that.field); } return false; }
  11. sbordet@webtide.com Java 14 - Pattern Matching • Another example: static

    String format(Object obj) { if (obj instanceof Integer i) { return String.format("int %d", i); } if (obj instanceof Float f) { return String.format("float %f", f); } return String.format("obj %s", obj); }
  12. sbordet@webtide.com Helpful NullPointerException

  13. sbordet@webtide.com Java 14 - Helpful NullPointerException • JEP 358: Helpful

    NullPointerException • -XX:+ShowCodeDetailsInExceptionMessages var a = c.b.a; Exception in thread "main" java.lang.NullPointerException: Cannot read field "a" because "c.b" is null
  14. sbordet@webtide.com Text Blocks

  15. sbordet@webtide.com Java 14 - Text Blocks • JEP 368 -

    Text Blocks (second preview) String json = """ __{"o": "JUG Torino", __"y": 2001 }"""; => "{\"o\": \"JUG Torino\",\n__\"y\": 2001\n}"
  16. sbordet@webtide.com • Margin Management String json = """ ____{ _____"o":

    "JUG Torino", _____"y": 2001 ____} ___"""; => "_{__\"o\": \"JUG Torino\",\n__\"y\": 2001\n_}\n" Java 14 - Text Blocks
  17. sbordet@webtide.com Java 14 - Text Blocks • Special Cases String

    empty = """ """; String error = """{ }"""; Error: illegal text block open delimiter sequence
  18. sbordet@webtide.com Java 14 - Text Blocks • Special Cases ◦

    \s => inserts space ◦ \ => removes newline String sql = """ select *\s\ from users; """; => "select * from users;\n"
  19. sbordet@webtide.com Java 14 - Text Blocks • Concatenation String ohNo

    = """ { "id": \"""" + id + """ // cannot put dquote here ", "role": "admin" // must zero the indentation }"""; String phew = """ { "id": "${id}", "role": "admin" }""".replace("${id}", id);
  20. sbordet@webtide.com Foreign Memory Access

  21. sbordet@webtide.com Java 14 - Foreign Memory Access • JEP 370

    - Foreign Memory Access API (incubating) • MemorySegment ◦ A contiguous region of memory (spatially bounded) ◦ Explicitly deallocated (temporally bounded) • MemoryLayout ◦ A (named) description of a memory segment • Finally, struct and union in Java!
  22. sbordet@webtide.com Java 14 - Foreign Memory Access WARNING! C code!

    struct { double x; double y; } complex[128]; x y x y x y 0 1 2
  23. sbordet@webtide.com Java code class Complex { double x; double y;

    } var cxs = new Complex[128]; Java 14 - Foreign Memory Access WARNING! C code! struct { double x; double y; } complex[128]; x y x y x y 0 1 2 3 4 5 x hdr x y hdr y x hdr y 0 1 2
  24. sbordet@webtide.com Java 14 - Foreign Memory Access WARNING! C code!

    struct { double x; double y; } complex[128];
  25. sbordet@webtide.com Java code // 64-bit double var real = MemoryLayout.ofValueBits(64,

    ByteOrder.BIG_ENDIAN); var complex = MemoryLayout.ofStruct( real.withName("x"), real.withName("y") ); var shape = MemoryLayout.ofSequence(128, complex); Java 14 - Foreign Memory Access WARNING! C code! struct { double x; double y; } complex[128];
  26. sbordet@webtide.com Java 14 - Foreign Memory Access • Unions in

    Java // A real number in 64 bits. ValueLayout real = MemoryLayout.ofValueBits(64, ByteOrder.BIG_ENDIAN); // Struct. GroupLayout complex = MemoryLayout.ofStruct(real.withName("x"), real.withName("y")); GroupLayout polar = MemoryLayout.ofStruct(real.withName("rho"), real.withName("theta")); // Union. GroupLayout coords = MemoryLayout.ofUnion(complex.withName("complex"), polar.withName("polar"));
  27. sbordet@webtide.com Java 14 - Foreign Memory Access // A shape

    in a game. SequenceLayout shape = MemoryLayout.ofSequence(128, complex); var ys = shape.varHandle(long.class, PathElement.sequenceElement(), PathElement.groupElement("y")); ys.set(shape.baseAddress(), 1L, 13L); x y x y x y x y x 13 x y
  28. sbordet@webtide.com Java 14 - Foreign Memory Access // Use try-with-resources

    to close the segment. try (MemorySegment segment = MemorySegment.allocateNative(shape)) { // Translate the shape on the y axis. for (long i = 0; i < shape.elementCount().orElse(0); ++i) { // Get the current y coordinate. long y = (Long)ys.get(segment.baseAddress(), i); // Set the new y coordinate. ys.set(segment.baseAddress(), i, y + 1); } }
  29. sbordet@webtide.com Records

  30. sbordet@webtide.com Java 14 - Records • JEP 359: Records (Preview)

    • Records are immutable, final, data holder classes ◦ Typed tuples • Automatic constructor and getters ◦ Plus equals(), hashCode(), toString() public record MinMax(int min, int max) {}
  31. sbordet@webtide.com Java 14 - Records • Usage ◦ int m

    = minMax.min; // field access ◦ int m = minMax.max(); // getter access ◦ IntSupplier s = minMax::max; // getter access • Records can be customized ◦ Custom constructors ◦ Override equals(), hashCode() and toString() ◦ Add methods (both static and virtual) ◦ Fields cannot be named hashCode, toString, wait...
  32. sbordet@webtide.com Java 14 - Records public record MinMax(int min, int

    max) { public MinMax { // compact constructor if (min > max) throw new IllegalArgumentException(); } public MinMax(Histogram h) { // custom constructor this(h.min, h.max); } public static MinMax zero() { return new MinMax(0, 0); } public int avg() { return (min + max) / 2; } // warning: hides getter! public int max() { return 0; } }
  33. sbordet@webtide.com Java 14 - Records • Use cases for Records

    • Multiple return values ◦ MinMax minMax(int[] array) { ... } ◦ MinMax is more expressive than Pair<int, int> • DTOs ◦ But not JPA entities (mutable)
  34. sbordet@webtide.com Java 14 - Records • Temporary tuples: private static

    String longest(Stream<String> stream) { // Method-local record class. record StrLen(String s, int l) {} return stream.map(s -> new StrLen(s, s.length())) .max(Comparator.comparingInt(StrLen::l)) .map(sl -> sl.s) .orElse(null); }
  35. sbordet@webtide.com Java 14 - Records • Records & Pattern Matching

    • 1-1 relationship between data and class ◦ Easy to deconstruct a record, recursively record Pctl(int p50, int p90, int p95, int p99) {} record Stats(Pctl percentile, MinMax minMax) {}
  36. sbordet@webtide.com Java 14 - Records • In Java 15, with

    sealed classes, this should be possible: sealed interface Expr permits AddExpr, ConstExpr, ... {} record ConstExpr(int value) implements Expr {} record AddExpr(Expr a, Expr b) implements Expr {} int eval(Expr expr) { return switch (expr) { case ConstExpr(int v) -> v; case AddExpr(Expr lt, Expr rt) -> eval(lt) + eval(rt); ... }
  37. sbordet@webtide.com Java 14 - Records • Records & Value Types

    • Value Types => flat and dense object layout in memory ◦ But must give up identity and nullability • Records => data tuple and deconstruction ◦ But must give up extension, hiding and mutability • May need both at the same time
  38. sbordet@webtide.com Others

  39. sbordet@webtide.com Java 14 - Other Updates • Additions ◦ JEP

    349: JFR Event Streaming ◦ JEP 352: Non-Volatile Mapped Byte Buffers ◦ JEP 345: NUMA aware allocation for G1 ◦ JEP 364-5: ZGC on macOS + Windows • Deprecations ◦ JEP 362: Deprecate the Solaris and SPARC Ports (gone in Java 15) • Removals ◦ JEP 363: Remove CMS ◦ JEP 367: Remove the Pack200 Tools and API
  40. sbordet@webtide.com Conclusions

  41. sbordet@webtide.com Java 14 - Conclusions • Switch Expression • Records

    & Pattern matching ◦ Even more coming with Java 15 • Foreign Memory Access ◦ For hard-core data structures • Text Blocks • Goodbye CMS
  42. sbordet@webtide.com Java 14 - Updates • References • https://jdk.java.net/14/release-notes •

    New Features • Removed Features • Deprecated Features • API Differences with Java 13
  43. sbordet@webtide.com Questions?