Slide 1

Slide 1 text

[email protected] Java 14 - Updates @simonebordet

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

[email protected] Switch Expression

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

[email protected] Java 14 - Switch Expression ● Use yield 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; }

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

[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

Slide 9

Slide 9 text

[email protected] Pattern Matching for instanceof

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

[email protected] Helpful NullPointerException

Slide 13

Slide 13 text

[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

Slide 14

Slide 14 text

[email protected] Text Blocks

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

[email protected] Foreign Memory Access

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

[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

Slide 23

Slide 23 text

[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

Slide 24

Slide 24 text

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

Slide 25

Slide 25 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 14 - Foreign Memory Access WARNING! C code! struct { double x; double y; } complex[128];

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

[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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

[email protected] Java 14 - 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 34

Slide 34 text

[email protected] Java 14 - 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 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

[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

Slide 38

Slide 38 text

Slide 39

Slide 39 text

[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

Slide 40

Slide 40 text

[email protected] Conclusions

Slide 41

Slide 41 text

[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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

[email protected] Questions?