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.

Simone Bordet

May 14, 2020
Tweet

More Decks by Simone Bordet

Other Decks in Programming

Transcript

  1. [email protected] Simone Bordet • @simonebordet • [email protected] • Java Champion

    • Works @ Webtide • The company behind Jetty and CometD • JVM Tuning Expert
  2. [email protected] 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; }
  3. [email protected] 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; }
  4. [email protected] 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; }
  5. [email protected] 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; }
  6. [email protected] 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
  7. [email protected] 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; }
  8. [email protected] 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); }
  9. [email protected] 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
  10. [email protected] Java 14 - Text Blocks • JEP 368 -

    Text Blocks (second preview) String json = """ __{"o": "JUG Torino", __"y": 2001 }"""; => "{\"o\": \"JUG Torino\",\n__\"y\": 2001\n}"
  11. [email protected] • Margin Management String json = """ ____{ _____"o":

    "JUG Torino", _____"y": 2001 ____} ___"""; => "_{__\"o\": \"JUG Torino\",\n__\"y\": 2001\n_}\n" Java 14 - Text Blocks
  12. [email protected] Java 14 - Text Blocks • Special Cases String

    empty = """ """; String error = """{ }"""; Error: illegal text block open delimiter sequence
  13. [email protected] Java 14 - Text Blocks • Special Cases ◦

    \s => inserts space ◦ \ => removes newline String sql = """ select *\s\ from users; """; => "select * from users;\n"
  14. [email protected] 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);
  15. [email protected] 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!
  16. [email protected] Java 14 - Foreign Memory Access WARNING! C code!

    struct { double x; double y; } complex[128]; x y x y x y 0 1 2
  17. [email protected] 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
  18. [email protected] Java 14 - Foreign Memory Access WARNING! C code!

    struct { double x; double y; } complex[128];
  19. [email protected] 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];
  20. [email protected] 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"));
  21. [email protected] 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
  22. [email protected] 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); } }
  23. [email protected] 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) {}
  24. [email protected] 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...
  25. [email protected] 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; } }
  26. [email protected] 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)
  27. [email protected] 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); }
  28. [email protected] 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) {}
  29. [email protected] 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); ... }
  30. [email protected] 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
  31. [email protected] 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
  32. [email protected] 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
  33. [email protected] Java 14 - Updates • References • https://jdk.java.net/14/release-notes •

    New Features • Removed Features • Deprecated Features • API Differences with Java 13