Java 23 and Beyond - A Roadmap Of Innovations

AnaMariaMihalceanu1 143 views 47 slides Sep 11, 2024
Slide 1
Slide 1 of 47
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47

About This Presentation

Slides for JUG Noord


Slide Content

JAVA 23 AND BEYOND
A ROADMAP OF INNOVATIONS
ANA-MARIA MIHALCEANU
Senior developer advocate at Oracle
ammbra1508 ammbra1508.mastodon.social

What Has Been Java Doing?
56
91
12
1…
8 5
16 14 1… 14
9 7 6
15
12 12
0
10
20
30
40
50
60
70
80
90
100
Features
(JEPs)
JDK 8JDK 9 JDK 10JDK 11 JDK 12JDK 13JDK 14JDK 15JDK 16JDK 17 JDK 18 JDK 19JDK 20 JDK 21
Mar
2024
Co mmercial
Support
3 Years 2 Years
JDK 22
Co mmercial
Support
Sept
2023
Mar
2023
Sept
2022
Mar
2022
Sept
2021
Mar
2021
Sept
2020
Mar
2020
Sept
2019
Mar
2019
Sept
2018
Mar
2018
Sept
2017
Mar
2014
Sept
2024
JDK 23
Co mmercial
Support
Co mmercial
Support

Inclusive Development Experience
??????”Paving the On Ramp
As a result, it is easy to forget about the “small" programs
Java has been historically
successful in “big" systems
And we all start small
But, we want Java
to be successful
for small applications too
•OOP concepts should not overwhelm your first (or any
small) program
•The “on ramp" should lead smoothly onto the highway
”Paving the On Ramp”

A Simplified Beginning
Project Amber

// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Launch via single file execution (since JDK 11)
java HelloWorld.java
Use jshell for fast prototyping Java code
Towards A Simplified Beginning

Paving The On Ramp (In Preview)
// HelloWorld.java
void main( ) {
println("Hello, World!");
}
publicclassHelloWorld {
publicstatic String[] args
}
System.out.
JEP 477: Implicitly Declared Classes and Instance Main Methods (Third Preview)

Effective Scripting with Java
// HelloWorld.java
void main() {
println("Hello, World!");
}
JEP 477: Implicitly Declared Classes and Instance Main Methods (Third Preview)
Class declaration no longer required
main is not necessarily public static
String[] args not declared if not used further
Auto-import useful methods for textual input and output

One Command To Launch Them All
// HelloWorld.java
class HelloWorld {
void main() {
Helper.run();
}
}
// Helper.java
class Helper {
static void run() {
println("Hello World!");
}
}
java --enable-preview -HelloWorld.java
JEP 458: Launch Multi-File Source-Code Programs
22

Thoughtful Evolution of Java
Language Features
Project Amber

Agenda Prototype
•Add chores to do to.
•Delete a chore when is done.
•A chore can have either an URL or an image attached to it.
•The deadline for chore has to be greater than current date.
•The priority is deduced based on deadline.

Agenda Entity Modeling
Sealed typeslimit which subtypes can directly
extend/implement them.
public sealed interface Todo
permits TodoItem {}
public non-sealed class TodoItem
implements Todo {}
public final class URLTodoItem
extends TodoItem{}
public final class ImageTodoItem
extends TodoItem{}

Inheritance and Constructor Chaining
public final class URLTodoItem extends TodoItem {
private String url;
public URLTodoItem(String title, String description, String url,
LocalDate createdOn, LocalDate deadline) {
super(title, description, createdOn, validate(createdOn, deadline));
this.url = url;
}
private static LocalDate validate(LocalDate createdOn, LocalDate deadline) {
if (deadline.isBefore(createdOn))
throw new IllegalArgumentException(”Deadline must not be before creation date" );
return deadline;
}
}
Constructor chaining is enforced in subclass.

Statements before super(…) (in preview)
public final class URLTodoItem extends TodoItem {
private String url;
public URLTodoItem(String title, String description, String url,
LocalDate createdOn, LocalDate deadline) {
if (deadline.isBefore(createdOn))
throw new IllegalArgumentException(”Deadline cannot be before creation date");
this.url = url;
super(title, description, createdOn, deadline);
}
}
Validate superclass constructor arguments
Prepare superclass constructor arguments
Share superclass constructor argumentsJEP 482: Flexible Constructor Bodies (Second Preview)

Determine Emergency Based on Priority
private static Highlight findColor(TodoItem item) {
return switch (item.getPriority()) {
case long p when p < 0 -> Highlight.RED;
case 0L -> Highlight.YELLOW;
case 1L -> Highlight.BLUE;
case long _ -> Highlight.WHITE;
};
}
JEP 455: Primitive Types in Patterns, instanceof, and switch (Preview)

Primitive Type Patterns in Nested Context
public record Statistic(Highlight highlight, int count) {}
switch (statistic) {
case Statistic(Highlight h, byte b) when h == Highlight.RED && b < -10 -> …;
case Statistic(Highlight h, short s) when h == Highlight.YELLOW -> …;
case Statistic(Highlight h, int i) when h == Highlight.BLUE ->…;
case Statistic(Highlight h, int i) -> …;
}
JEP 455: Primitive Types in Patterns, instanceof, and switch (Preview)

Import All Packages Exported by a Module
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import module java.base;
JEP 476: Module Import Declarations (Preview)

So You Want to Know More…
•Java 23: Restoring the Balance with Primitive Patterns - Inside Java Newscast #66
•Clean Application Development with Records, Sealed Classes and Pattern Matching (2022)
•Java Records are "Trusted" and Consequently Faster
•State of Pattern Matching with Brian Goetz (2022)
•Pattern Matching in the Java Object Model
•Patterns: Exhaustiveness, Unconditionality, and Remainder
•Uniform handling of failure in switch

Fundamental Changes to
Achieve Your Application Goals
Core Libraries

A New Form of Documentation Comment
Markdown in Java documentation comments help with having:
•concise syntax for common constructs,
•reduce the dependence on HTML markup and JavaDoc tags,
•while keep enabling the use of specialized tags when not available in Markdown.
JEP 467: Markdown Documentation Comments

Valid Markdown Documentation Comments
Platform rules to identify the content of a Markdown documentation comment:
•Any leading whitespace and the three initial/characters are removed from each line.
•Then, the lines are shifted left, by getting rid of any extra spaces at their start.
•Any spaces that are part of the text itself are kept as those might actually mean something, like
starting a new code block.
JEP 467: Markdown Documentation Comments

Extra Capabilities
•Define simple GitHub Flavored Markdown pipe tables.
•Process standalone Markdown files fromdoc-filessubdirectories.
•Standalone Markdown files can have JavaDoc tags , but YAML metadata is not supported.
•Enable syntax highlighting with Javascript libraries through javadoc --add-script.
•Render diagrams (like Mermaid).
JEP 467: Markdown Documentation Comments

Unfulfilled Streams Operations
• Streams API has a fixed set of intermediate operations.
List<String> letters = Arrays.asList("A","B","C","D","E","F","G","H");
int size = 3;
// ABC DEF GH
IntStream.range(0, (letters.size() + size - 1) / size)
.mapToObj(i -> String.join("",
letters.subList(i * size, Math.min(size * (i + 1), letters.size()))))
.toList();
Some intermediate operations are missing: sliding windows, take-while-including, fixed grouping,etc.

Enter Gatherers API (in preview)
•A generalization for intermediate operations java.util.stream.Gatherer
•A new intermediate stream operation to process elements of a stream:Stream::gather(Gatherer)
•A few implementations, e.g.Gatherers.fold(…), Gatherers.windowFixed(…).
•A way to compose gathererers source.gather(a.andThen(b).andThen(c)).collect(...).
List<String> letters = Arrays.asList("A","B","C","D","E","F","G","H");
int size = 3;
letters.stream()
.gather(Gatherers.windowFixed(3))
.map(window -> String.join("", window))
.toList();
JEP 473: Stream Gatherers (Second Preview)

Gatherer Components
Initializer (optional)
•Creates private state object
Integrator (mandatory)
•Accepts(state, element, downstream)
•Integrateselement into state
•to update gatherer’s privatestate object
•to emit 0+ element(s) to downstream
Combiner (optional)
•Can evaluate the gatherer in parallel
Finisher (optional)
•Accepts(state, downstream)
•Invoked when no moreelements can be consumed
•Emits element(s) to downstream

Compiling And Launching a Java Program
IDE
javac java
.java source
file
bytecode .class
file
Program running

Bytecode Manipulation
Runtime
JVM
Class
loader
.class
javac
jdeps
libraires
agents
frameworks

The New Class-file API (in preview)
•A stable Java API for analyzing and manipulating bytecode.
•An API always-up-to-date with the JDK version.
•Frameworks that use this API can easily update to a newer JDK version.
JEP 466: Class-File API (Second Preview)

So You Want to Know More…
•JavaDoc Hits the Markdown on Comments - Inside Java Newscast #68
•A Classfile API for the JDK(JVMLS 2023, Brian Goetz)
•New Class-File API will make Java Updates easier - Inside Java Newscast #56
•Teaching Old Streams New Tricks(Devoxx Belgium 2023, Viktor Klang)
•Better Java Streams with Gatherers - Inside Java Newscast #57

The Scalable, Low-latency
Generational ZGC
HotSpot

ZGC at a Glance
•Delivered in JDK 15 (September 2020)
•A scalable low-latency garbage collector
•ZGC pauses are O(1)
•Scalable: up to TB heaps
•Auto-tuning: requires minimal configuration
•Can handle heaps ranging from a8MBto16TBin size

Benefits of Generational ZGC
•Withstand higher allocation rates
•Lower heap headroom
•Lower CPU usage
•Now enabled by default when using -XX:+UseZGC
•Automatic Tuning -> Only set the max heap size! (-Xmx)
JEP 474: ZGC: Generational Mode by Default

What Changed?
•Did you enable ZGC it with -XX:+UseZGC -XX:+ZGenerational?
•Generational ZGC is used.
Warning that theZGenerationaloption is deprecated is issued.
•Do you still need non-generational ZGC?
•You can enable it via -XX:+UseZGC -XX:-ZGenerational.
Warning that theZGenerationaloption is deprecated is issued.
Warning that the non-generational mode is deprecated for removal is issued.
JEP 474: ZGC: Generational Mode by Default

So You Want to Know More…
•Overview of ZGC
•Deep-dive of zgc's architecture
•JVMLS - generational ZGC and beyond
•Optimizing memory utilization with automated heap sizing in ZGC
•Z garbage collector: the next generation
•ZGC : java’s highly scalable low-latency garbage collector - stack walker #1

Safe Concurrent Programming
Project Loom

Virtual Threads Adoption

Let’s Revisit Our Agenda
•Add chores to do to.
•Delete a chore when is done.
•A chore can have either an URL or an image attached to it.
•The deadline for chore has to be greater than current date.
•The priority is deduced based on deadline.
•Parse csv todo files when starting the application.

Structured Concurrency to the Rescue
// Success/failure policy can be defined across all children.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var baseTodo = scope.fork(() -> parseCSV(todoFile));
var urlTodo = scope.fork(() -> parseCSV(urlFile));
var mixTodo = scope.fork(() -> parseCSV(mixFile));
scope.join();
scope.throwIfFailed(IllegalStateException::new);
List<List<String>> data = baseTodo.get();
data.addAll(urlTodo.get());
data.addAll(mixTodo.get());
}
JEP 480: Structured Concurrency (Third Preview)

Simplify Data Flow Reasoning
public static ScopedValue<String> VALID_FILE = ScopedValue.newInstance();
ScopedValue.callWhere(VALID_FILE, todoFilePath, () ->
TodoFile.processContent(todoFilePath, urlFilePath, mixFilePath));
public static class FileScope extends StructuredTaskScope<TodoFile> {
//...
try (var scope = new FileScope()) {
scope.fork(() -> parseCSV(todoFile));
scope.fork(() -> parseCSV(urlFile));
scope.fork(() -> parseCSV(mixFile));
scope.join();
return scope.processContent();
}
}
JEP 481: Scoped Values (Third Preview)

Benefits for High Scaling Applications
Higher throughput with fewer CPU
operations when havinghigh number
concurrent requests.
When having blocking calls, virtual
threads will go in a waiting state until they
receive data.

So You Want to Know More…
•Structured Concurrency
•On Parallelism and Concurrency
•Java 20 - From ThreadLocal to ScopedValue with Loom Full Tutorial - JEP Café #16
•Latest news on Project Loom

Broadened Ability to Develop
High-Performance Programs

Protecting Java Code from the JVM Up
•We rely on the integrity of our code, meaning it is correct and complete.
•There are 4 APIs in JDK that can bypass integrity:
•TheAccessibleObject::setAccessible(boolean)method in thejava.lang.reflect package
•Thesun.misc.Unsafeclass with methods that can access private methods and fields
•TheJava Native Interface (JNI)
•The Instrumentation API allows agents to modify the bytecode of any method in any class.
•JEP 471 showcases the impact of sun.misc.Unsafe memory-access methods + offers migration examples.
JEP 471: Deprecate the Memory-Access Methods in sun.misc.Unsafe for Removal

Project Summary Pain point “Obvious"
Competition
Amber Right-sizing language ceremony
“Java is too verbose"
“Java is hard to teach"
C#, Kotlin
Babylon Foreign programming model interop “Using GPUs is too hard" LinQ, Julia
Leyden Faster startup and warmup “Java starts up too slowly" Go
Loom Lightweight concurrency
“Threads are too expensive, don’t
scale"
Go, Elixir
Panama
Native code and memory interop
SIMD Vector support
“Using native libraries is too hard"
“Numeric loops are too slow"
Python, C
Valhalla Value types and specialized generics
“Cache misses are too expensive"
“Generics and primitives don’t mix"
C, C#
ZGC Sub-millisecond GC pauses “GC pauses are too long" C, Rust

Learn, Share, and Collaborate

Stay Tuned for More
Inside.javaDev.java youtube.com/java

THANK YOU!
Code