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

Day of the Dukentacle : la meilleure façon de prévoir le futur, c'est de le fabriquer soi-même

José
April 18, 2024
110

Day of the Dukentacle : la meilleure façon de prévoir le futur, c'est de le fabriquer soi-même

Alors que Java 21 est à présent derrière nous, il est temps de se tourner vers la prochaine version LTS, qui sera présente dans 18 mois, et disponible en préversion dans à peine plus d'un an. Plusieurs éléments de Java 22 portent en germe ce que seront les principales nouveautés de cette future version. On se propose d'en passer certaines en revue, qui vont faire évoluer le langage et ses API fondamentales, telles qu'Object ou String, et changer la façon dont on écrit du code Java. On parlera de variables sans nom, de classes implicites, de scripts Java, de nouvelles façons d'initialiser les objets, de nouvelles façons de gérer la mémoire explicitement, et bien sûr, de l'interpolation des chaînes de caractères, chantier ouvert il y a plusieurs années déjà. Le futur s'écrit aujourd'hui, pour un langage plus simple, plus logique, et des API plus puissantes et plus performantes.

José

April 18, 2024
Tweet

Transcript

  1. Day of the Dukentacle Fabriquons le futur de peur qu’il

    ne nous fabrique! José Paumard Java Developer Advocate Java Platform Group Rémi Forax Maître de conferences Université Gustave Eiffel
  2. https://twitter.com/He bah non! https://github.com/forax https://speakerdeck.com/forax OpenJDK, ASM, Tatoo, Pro, etc…

    One of the Father of invokedynamic (Java 7) Lambda (Java 8), Module (Java 9) Constant dynamic (Java 11) Record, text blocks, sealed types (Java 14 / 15) Valhalla (Java 23+)
  3. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 4 Covering

    several new things in the Java language First part: - Unnamed classes (JEP 445, JEP 458) - Unnamed patterns (JEP 456) - String Template (JEP 465) What’s in it for you?
  4. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 5 Covering

    several new things in the Java language Second part: - Statement before super (JEP 447) - Foreign Function & Memory API (JEP 454) What’s in it for you?
  5. Tune in! Copyright © 2021, Oracle and/or its affiliates |

    7 Inside Java Newscast JEP Café Road To 21 series Inside.java Inside Java Podcast Sip of Java Cracking the Java coding interview
  6. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 11 String

    Template Processor Creating a Validating Templates API
  7. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 12 Who

    loves JavaScript ? Who is using JS for front end dev ? Who is using - React? - Angular? - Vue? - Svelte? Going Sideway
  8. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 14 Coupling

    View / API? View Browser REST API Model DB Server AJAX JSON JSON
  9. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 15 Conceptually,

    an extension of HTML Add 3 kind of attributes - hx-trigger - hx-post, hx-get, hx-delete, etc + hx-vals - hx-target + hx-swap Server-side rendering != react SSR </> htmx
  10. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 16 The

    API Should Serve the UI htmx (JS) Browser UI API Model DB Server AJAX Params XML
  11. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 17 We

    want to generate HTML/XML hx-trigger - Could be JSON, SQL, etc… - With holes for values from the current context The values should be properly escaped - No SQL injection, etc… The result is not necessary a String String Template Processor
  12. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 18 String

    Template Processor STR."Hello \{user.getName()}" FMT."Your age: %d\{x + 3}"
  13. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 19 XML

    template processor + composition html-component record Product(String name, int price) implements Component { public Renderer render() { return $.""" <tr class=".product"> <td>\{name}</td><td>\{price * 1.20}</td> </tr> """; } } https://github.com/forax/html-component
  14. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 21 Not

    a String Not a StringTemplate (fragments + values) An interface that - Validates fragments - Interpolates values using the correct escaping String Template Processor
  15. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 23 A

    plain old static method is more powerful No need for a special syntaxe Long Live StringTemplate Methods! public static Renderer XML(StringTemplate template) { ... }
  16. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 24 No

    need for a special syntax Long Live StringTemplate Methods! public Renderer render() { return XML($.""" <tr class=".product"> <td>\{name}</td><td>\{price * 1.20}</td> </tr> """); }
  17. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 25 Separating

    the validation and the interpolation? - The validation is done only once Where Can We Go? class XMLDOM { static XMLDOM of(StringTemplate template) { ... } }
  18. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 26 Separating

    the validation and the interpolation? - The validation is done only once - The interpolation is done using the validated object Where Can We Go? static Renderer XML(XMLDom dom, Object... args) { ... }
  19. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 28 Does

    it have to be the first instruction of a constructor? Call to super() class A { A() { super(); // calls Object() } } class B extends A { B() { super(); // calls A() } }
  20. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 29 If

    new B(null), all the fields of A are initialized before B is discovered as invalid It Delays Precondition Checks class Named { String name; Named(String name) { this.name = name; } } class Student extends Named { Student(String name) { super(name); Objects.requireNonNull(name); } }
  21. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 30 Computation

    has to be done inside the call to super(...) It Makes the Code Less Readable class Hashed { int hash; Hashed(int hash) { this.hash = hash; } } class Named extends Hashed { String name; Named(String name) { super(Utils.hash(name)); this.name = name; } }
  22. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 31 Computation

    has to be done inside the call to super(...) It Makes the Code Less Readable class Hashed { int hash; Hashed(int hash) { this.hash = hash; } } class Named extends Hashed { String name; Named(String name) { var hash = Utils.hash(name) super(hash); this.name = name; } }
  23. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 32 Javac

    generates the code before the call to super(…) Code Before super()? interface Expr { int eval(); static Expr add(int a, int b) { return new Expr() { public int eval() { return a + b; } }; } } 0: aload_0 1: iload_1 2: putfield // val$a:I 5: aload_0 6: iload_2 7: putfield // val$b:I 10: aload_0 11: invokespecial // Object."<init>":()V 14: return
  24. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 35 Two

    issues - Does not work with the Record canonical constructor - Can not initialize fields before super(...) What’s Next?
  25. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 36 Flexible

    Constructor Bodies (Second Preview) What’s Next? Draft JEP
  26. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 37 Value

    types are unmodifiable Valhalla? value class Optional<T> { private final T value; private Optional(T value) { this.value = value; // initialization before super() super(); } static <T> Optional<T> empty() { return new Optional<>(null); } static <T> Optional<T> of(T value) { return new Optional<>(value); } }
  27. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 40 It

    is about accessing the off heap memory This memory is not handled by the Garbage Collector The GC: - Gives you the memory to store your objects - Tracks if what it gives you is still in use or not - Reclaims it if not Drawback: GCs like to move your objects around What is it about?
  28. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 41 Why

    would you store information off heap? - You can store raw data (≠ unstructured) - You can directly store data coming from your I/O (buffers don’t like to be moved around) - You can read and process it very efficiently Why do you need off heap memory?
  29. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 42 Two

    of them: 1) The ByteBuffer API - API from Java NIO (Java 4, 2002) - No type safety - Limited to 2 GB (indexed by an int) - The memory is reclaimed when the ByteBuffer object is garbaged What are the alternatives?
  30. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 43 Two

    of them: 2) The infamous sun.misc.Unsafe API - Unsafe… - Unsafe doesn’t mean fast, it means unsafe The Memory API aims to fix all this What are the alternatives?
  31. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 44 1)

    It is fast 2) There is no 2 GB limit 3) You can choose between unsafe or type safety 4) You can reclaim the memory on demand 5) You can control the thread safety 6) Access is bound in space and time The Memory API fixes all this
  32. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 45 First,

    get an arena How is it working? Arena arena = Arena.global();
  33. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 46 Then,

    get a memory segment from this arena How is it working? Arena arena = Arena.global(); MemorySegment segment = arena.allocate(80L, 1L);
  34. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 47 Then,

    add some data in this memory segment How is it working? Arena arena = Arena.global(); MemorySegment segment = arena.allocate(80L, 1L); for (long index; index < 10L; index++) { segment.setAtIndex( ValueLayout.JAVA_LONG, index, random.nextLong(0L, 100L)); }
  35. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 48 And

    then, read it back How is it working? for (long index; index < 10L; index++) { var l = segment.getAtIndex( ValueLayout.JAVA_LONG, index); }
  36. Arena 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 49

    MemorySegment MemorySegment MemorySegment int int int int int long int int double MemorySegment int int int MemorySegment int long int int double
  37. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 50 An

    arena is a factory to create memory segment What is this Arena object? public interface Arena extends SegmentAllocator, AutoCloseable { }
  38. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 51 An

    arena is a factory to create memory segment There are four of them: What is this Arena object? var global = Arena.global(); // singleton var auto = Arena.ofAuto(); var confined = Arena.ofConfined(); var shared = Arena.ofShared();
  39. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 52 An

    arena is a factory to create memory segment There are four of them: What is this Arena object? Closeable Bounded Lifetime Shared among threads Global No Auto No Confined Yes Shared Yes
  40. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 53 An

    arena is a factory to create memory segment There are four of them: What is this Arena object? Closeable Bounded Lifetime Shared among threads Global No No Auto No Yes Confined Yes Yes Shared Yes Yes
  41. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 54 An

    arena is a factory to create memory segment There are four of them: What is this Arena object? Closeable Bounded Lifetime Shared among threads Global No No Yes Auto No Yes Yes Confined Yes Yes Shared Yes Yes
  42. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 55 An

    arena is a factory to create memory segment There are four of them: What is this Arena object? Closeable Bounded Lifetime Shared among threads Global No No Yes Auto No Yes Yes Confined Yes Yes No Shared Yes Yes Yes
  43. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 56 A

    MemorySegment is an interface A MemorySegment is a contiguous segment of memory A segment can be: - A heap segment, on-heap - Or a native segment, off-heap More about the MemorySegment public sealed interface MemorySegment { }
  44. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 57 A

    on-heap MemorySegment is built on an array On-Heap MemorySegment int[] ints = new int[...]; var segment = MemorySegment.ofArray(ints);
  45. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 58 A

    MemorySegment is a contiguous segment of memory More about the MemorySegment segment
  46. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 59 You

    can model the content of a MemorySegment with the MemoryLayout interface Modeling with MemoryLayout public sealed interface MemoryLayout { }
  47. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 60 ValueLayout.JAVA_LONG

    tells that this segement is holding long primitive types Modeling with MemoryLayout for (long index; index < 10L; index++) { segment.setAtIndex( ValueLayout.JAVA_LONG, index, random.nextLong(0L, 100L)); }
  48. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 61 The

    MemoryLayout interface ValueLayout models all the primitive types sealed interface ValueLayout extends MemoryLayout permits ValueLayout.ofByte, ValueLayout.ofShort, ValueLayout.OfInt, ValueLayout.ofLong ValueLayout.ofFloat, ValueLayout.ofDouble, ValueLayout.ofChar, ValueLayout.ofBoolean { }
  49. 0 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 62

    setAtIndex() accesses the indexth int Modeling with MemoryLayout for (long index; index < 10L; index++) { segment.setAtIndex( ValueLayout.JAVA_INT, index, random.nextInt(0L, 100L)); } 1 2
  50. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 63 set()

    accesses the indexth cell Modeling with MemoryLayout for (long index; index < 10L; index++) { segment.set( // = set at offset ValueLayout.JAVA_INT, index, random.nextInt(0L, 100L)); } 0 1 2
  51. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 64 There

    two others memory layouts: - a layout to model structs - a layout to model fixed-size arrays - a padding layout - a union layout Other MemoryLayouts
  52. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 65 Suppose

    you need to read the following struct The Struct MemoryLayout struct Point { int x; int y; } points;
  53. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 66 First

    define a struct layout Modeling with MemoryLayout var pointLayout = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y"));
  54. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 67 First

    define a struct layout Why do you need the names x and y? Modeling with MemoryLayout var pointLayout = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y"));
  55. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 68 You

    can access all these elements using a var handle VarHandle is a class added to Java 9 Added after the MethodHandle class in Java 7 Getting a Varhandle From a MemoryLayout
  56. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 69 1)

    Define a var handle on any of the field of the struct Defining a Var Handle var pointLayout = MemoryLayout.structLayout( ValueLayout.JAVA_INT.withName("x"), ValueLayout.JAVA_INT.withName("y")); var xHandle = pointLayout.varHandle( MemoryLayout.PathElement.groupElement("x")) .withInvokeExactBehavior();
  57. 4/18/2024 Copyright © 2023, Oracle and/or its affiliates 70 2)

    Use the var handle to read or write this field Defining a Var Handle var xHandle = pointLayout.varHandle( MemoryLayout.PathElement.groupElement("x")) .withInvokeExactBehavior(); int x = (int) xHandle.get(segment, 0L); xHandle.set(segment, 0L, 1234);