Slide 1

Slide 1 text

[email protected] Java 15 - Updates @simonebordet

Slide 2

Slide 2 text

[email protected] Simone Bordet ● @simonebordet ● [email protected] ● Java Champion ● Works @ Webtide ● The company behind Jetty and CometD

Slide 3

Slide 3 text

[email protected] Java 15 Confirmed Features

Slide 4

Slide 4 text

[email protected] Text Blocks

Slide 5

Slide 5 text

[email protected] Java 15 - Text Blocks ● Text Blocks String json = """ __{"o": "JUG Torino", __"y": 2001 __}"""; => "{\"o\": \"JUG Torino\",\n\"y\": 2001\n}"

Slide 6

Slide 6 text

[email protected] ● Margin Management String json = """ ____{ _____"o": "JUG Torino", _____"y": 2001 ____} ___"""; => "_{__\"o\": \"JUG Torino\",\n__\"y\": 2001\n_}\n" Java 15 - Text Blocks

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

[email protected] Java 15 - Text Blocks ● Special Cases ○ \s => inserts space ○ \ => removes newline String sql = """ select *\s\ from users; """; => "select * from users;\n"

Slide 9

Slide 9 text

[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);

Slide 10

Slide 10 text

[email protected] Java 15 Second Previews

Slide 11

Slide 11 text

[email protected] Pattern Matching for instanceof

Slide 12

Slide 12 text

[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; }

Slide 13

Slide 13 text

Slide 14

Slide 14 text

[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) {}

Slide 15

Slide 15 text

[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...

Slide 16

Slide 16 text

[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; } }

Slide 17

Slide 17 text

[email protected] Java 15 - Records ● Use cases for Records ● Multiple return values ○ MinMax minMax(int[] array) { ... } ○ MinMax is more expressive than Pair ● DTOs ○ But not JPA entities (mutable)

Slide 18

Slide 18 text

[email protected] Java 15 - Records ● Temporary tuples: private static String longest(Stream 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); }

Slide 19

Slide 19 text

[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) {}

Slide 20

Slide 20 text

[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

Slide 21

Slide 21 text

[email protected] Foreign Memory Access

Slide 22

Slide 22 text

[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!

Slide 23

Slide 23 text

[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

Slide 24

Slide 24 text

[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

Slide 25

Slide 25 text

[email protected] Java 15 - Foreign Memory Access WARNING! C code! struct { double x; double y; } complex[128];

Slide 26

Slide 26 text

[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];

Slide 27

Slide 27 text

[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"));

Slide 28

Slide 28 text

[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

Slide 29

Slide 29 text

[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); } }

Slide 30

Slide 30 text

[email protected] Java 15 First Preview

Slide 31

Slide 31 text

[email protected] Sealed Classes

Slide 32

Slide 32 text

[email protected] Java 15 - Sealed Classes sealed interface Celestial permits Star, Planet, Satellite {}

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

[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 {} }

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

[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; } }

Slide 38

Slide 38 text

[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; } } }

Slide 39

Slide 39 text

[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); ... }

Slide 40

Slide 40 text

[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 {}

Slide 41

Slide 41 text

[email protected] Java 15 Other Features

Slide 42

Slide 42 text

[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

Slide 43

Slide 43 text

[email protected] Conclusions

Slide 44

Slide 44 text

[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

Slide 45

Slide 45 text

[email protected] Java 15 - Updates ● References ● https://jdk.java.net/15/release-notes ● New Features ● Removed Features ● Deprecated Features ● API Differences with Java 14

Slide 46

Slide 46 text

[email protected] Questions?