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

Java 15 - Updates

Java 15 - Updates

A presentation about the updates introduced in Java 15.

Text Blocks, Pattern Matching for instanceof, Foreign Memory Access APIs, Sealed Classes, Records and Goodbye Nashorn.

Simone Bordet

October 01, 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
  2. [email protected] Java 15 - Text Blocks • Text Blocks String

    json = """ __{"o": "JUG Torino", __"y": 2001 __}"""; => "{\"o\": \"JUG Torino\",\n\"y\": 2001\n}"
  3. [email protected] • Margin Management String json = """ ____{ _____"o":

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

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

    \s => inserts space ◦ \ => removes newline String sql = """ select *\s\ from users; """; => "select * from users;\n"
  6. [email protected] Java 15 - 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);
  7. [email protected] Java 15 - Pattern Matching • 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 15 - Records • Records • Records are

    immutable, final, data holder classes ◦ Typed tuples • Automatic constructor and getters ◦ Plus equals(), hashCode(), toString() public record MinMax(int min, int max) {}
  9. [email protected] Java 15 - Records • Usage ◦ int m

    = minMax.max; // 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...
  10. [email protected] Java 15 - 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! don’t do it! public int max() { return 0; } }
  11. [email protected] Java 15 - 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)
  12. [email protected] Java 15 - 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); }
  13. [email protected] Java 15 - 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) {}
  14. [email protected] Java 15 - 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
  15. [email protected] Java 15 - Foreign Memory Access • Foreign Memory

    Access API (second incubation) • 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 15 - 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 15 - 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 15 - 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 15 - Foreign Memory Access WARNING! C code! struct { double x; double y; } complex[128];
  20. [email protected] Java 15 - 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 15 - Foreign Memory Access // A shape

    in a game. SequenceLayout shape = MemoryLayout.ofSequence(3, 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 15 - 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 15 - Sealed Classes sealed interface Celestial permits

    Star, Planet, Satellite {} final class Planet implements Celestial {}
  24. [email protected] Java 15 - Sealed Classes sealed interface Celestial permits

    Star, Planet, Satellite {} final class Planet implements Celestial {} non-sealed class Star implements Celestial {}
  25. [email protected] Java 15 - Sealed Classes sealed interface Celestial permits

    Star, Planet, Satellite {} final class Planet implements Celestial {} non-sealed class Star implements Celestial {} sealed class Satellite implements Celestial permits Satellite.Natural, Satellite.Artificial { final class Artificial extends Satellite {} final class Natural extends Satellite {} }
  26. [email protected] Java 15 - Sealed Classes sealed class Shape permits

    Circle, Rectangle {} • How do you implement Shape.getArea()?
  27. [email protected] Java 15 - Sealed Classes sealed class Shape permits

    Circle, Rectangle { abstract double getArea(); } record Circle(double r) implements Shape { @Override double getArea() { return Math.PI * r * r; } }
  28. [email protected] Java 15 - Sealed Classes sealed class Shape permits

    Circle, Rectangle { double getArea() { // Enhanced switch from Java 16. return switch (this) { case Circle(double r) -> Math.PI * r * r; case Rectangle(double h, double w) -> h * w; } } }
  29. [email protected] Java 15 - Sealed Classes • Sealed Classes &

    Records sealed interface Expr permits AddExpr, ConstExpr, ... {} record ConstExpr(int value) implements Expr {} record AddExpr(Expr a, Expr b) implements Expr {} // Enhanced switch from Java 16. static 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 15 - Sealed Classes • Use sealed classes

    to restrict implementations • enum -> same implementation, different values • sealed -> different implementations • Use sealed & records for simple and known domains ◦ sealed class Optional permits None, Some {}
  31. [email protected] Java 15 - Other Updates • Additions ◦ JEP

    371: Hidden Classes ◦ JEP 373: Reimplement the Legacy DatagramSocket API ◦ JEP 377: ZGC: A Scalable Low-Latency Garbage Collector ◦ JEP 379: Shenandoah: A Low-Pause-Time Garbage Collector • Deprecations ◦ JEP 374: Disable and Deprecate Biased Locking ◦ JEP 385: Deprecate RMI Activation for Removal • Removals ◦ JEP 381: Remove the Solaris and SPARC Ports ◦ JEP 372: Remove the Nashorn JavaScript Engine
  32. [email protected] Java 15 - Conclusions • Text Blocks • Sealed

    Classes, Records & Pattern matching ◦ Still in preview • Foreign Memory Access ◦ For hard-core data structures • Goodbye Nashorn • Goodbye Solaris & SPARC
  33. [email protected] Java 15 - Updates • References • https://jdk.java.net/15/release-notes •

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