SlideShare a Scribd company logo
Java 22 and Beyond
A Roadmap of Innovations
Java Champion Alumni, Certified Architect
Senior Developer Advocate at Oracle
Passionate about solving complex scenarios
involving Java and Kubernetes.
ammbra1508.mastodon.social
ammbra1508
“The only way you can predict the
future is to build it"
Alan Kay
Download and give it try: https://jdk.java.net/22/
6-month Release Cadence
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
Java in the Small
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 things too
• OOP concepts such as access control and static-ness
should not overwhelm your first (or any small) program
• The “on ramp" should lead smoothly onto the highway
“Paving the On Ramp"
A Simplified Begining
Project Amber
Towards a Simplified Beginning
// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Use jshell for fast prototyping Java code
Launch via single file execution (since JDK 11)
java HelloWorld.java
Paving the On Ramp (in preview)
// HelloWorld.java
void main() {
System.out.println("Hello, World!");
}
JEP 463: Implicitly Declared Classes and Instance Main Methods (Second Preview)
Class declaration no longer required
main is not necessarily public static
String[] args not declared if not used further
Invocation Order when Selecting Main
☕ A static void main(String[] args) method of non-private access in the launched class.
☕ A static void main() method with non-private access in the launched class.
☕ A non-private void main(String[] args) instance method in the launched class/inherited from a
superclass.
☕ A non-private void main() instance method in the launched class or inherited from a superclass.
One Command to Launch Them All
// HelloWorld.java
class HelloWorld {
void main() {
Helper.run();
}
}
◦
// Helper.java
import static java.lang.System.out;
class Helper {
static void run() {
out.println("Hello World!");
}
}
JEP 458: Launch Multi-File Source-Code Programs
java --enable-preview --source 22 HelloWorld.java
So you want to know more…
☕ JEP 463: Implicitly Declared Classes and Instance Main Methods (Second Preview)
☕ Script Java Easily in 21 and Beyond - Inside Java Newscast #49
☕ JEP 458: Launch Multi-File Source-Code Programs
☕ Does Java 22 Kill Build Tools? - Inside Java Newscast #63
☕ JEP 477: Implicitly Declared Classes and Instance Main Methods (Third Preview)
Thoughtful Evolution of Java
Language Features
Project Amber
Wrapup Data Modeling
☕ A sender can do a nice gesture and offer a gift.
☕ A gift can only be either a postcard or add to it
one of the following: an online coupon, buy an
experience or a material present.
☕ A postcard does not have an associated cost, all
the other 3 types of products have a price.
☕ A sender can never send 2 postcards as a gift.
☕ An online coupon has an expiry date.
☕ A present can be placed inside a box.
☕ A coupon could be bought for sharing an
experience too.
Wrapup Data Modeling Detailed
☕ Sealed types limit which subtypes can directly
extend/implement them.
public sealed interface Intention
permits Coupon, Experience,
Present, Postcard {}
public sealed class Experience
implements Intention
permits Coupon {}
☕ Present,Postcard are records.
☕ Coupon extends Experience.
☕ Represent Gift using composite patterns.
Inheritance and Constructor Chaining
public final class Coupon extends Experience implements Intention {
private final LocalDate expiringOn;
public Coupon(double price, LocalDate expiringOn, Currency currency) {
super(verifyPositive(price), currency);
this.expiringOn = expiringOn;
}
private static double verifyPositive(double price) {
if (price < 0) {
throw new IllegalArgumentException("Price cannot be negative");
}
return price;
}
}
Constructor chaining is enforced in subclass.
Statements Before super(…) (in preview)
public final class Coupon extends Experience implements Intention {
private final LocalDate expiringOn;
public Coupon(double price, LocalDate expiringOn, Currency currency) {
if (price < 0) {
throw new IllegalArgumentException("Price cannot be negative");
}
super(price, currency);
this.expiringOn = expiringOn;
}
}
JEP 447: Statements before super(...) (Preview)
Validate superclass constructor arguments
Prepare superclass constructor arguments
Share superclass constructor arguments
Wrapup Expressive Data Modeling
☕ Sealed types limit which subtypes can directly
extend/implement them.
public sealed interface Intention
permits Coupon, Experience,
Present, Postcard {
//…
}
☕ Coupon,Experience,Present,Postcard
are records.
☕ Represent Gift using nested record patterns.
Record Patterns and Exhaustive Switch
JSONObject process(Gift gift, Choice choice) {
return switch (gift) {
case Gift(Postcard p, Postcard p2) -> new JSONObject(p);
case Gift(Postcard p, Coupon c) when (c.price() == 0.0) -> new JSONObject(p);
case Gift(Postcard p, Experience e) when (e.price() == 0.0) -> new JSONObject(p);
case Gift(Postcard p, Present pr) when (pr.itemPrice() == 0.0) -> new JSONObject(p);
case Gift(Postcard p, Experience e) -> gift.merge(choice.name().toLowerCase());
case Gift(Postcard p, Present pr) -> gift.merge(choice.name().toLowerCase());
case Gift(Postcard p, Coupon c) -> gift.merge(choice.name().toLowerCase());
};
}
Code Readability and Lower Error Chances
JSONObject process(Gift gift, Choice choice) {
return switch (gift) {
case Gift(Postcard p, Postcard _) -> new JSONObject(p);
case Gift(Postcard p, Coupon c) when (c.price() == 0.0) -> new JSONObject(p);
case Gift(Postcard p, Experience e) when (e.price() == 0.0) -> new JSONObject(p);
case Gift(Postcard p, Present pr) when (pr.itemPrice() == 0.0) -> new JSONObject(p);
case Gift(_, Coupon _), Gift(_, Experience _), Gift(_, Present _) -> {
String option = choice.name().toLowerCase();
yield gift.merge(option);
}
};
}
JEP 456: Unnamed Variables & Patterns
So You Want To Know More…
☕ 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
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 457: Class-File API (Preview)
So You Want To Know More…
☕ A Classfile API for the JDK (JVMLS 2023, Brian Goetz)
☕ New Class-File API will make Java Updates easier - Inside Java Newscast #56
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;
IntStream.range(0, (letters.size() + size - 1) / size)
.mapToObj(i -> String.join("",
letters.subList(i * size, Math.min(size * (i + 1), letters.size()))))
.toList();
// ABC
// DEF
// GH
☕ Some intermediate operations are missing: sliding windows, take-while-including, fixed grouping, scanning, 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 461: Stream Gatherers (Preview)
Integrator (mandatory)
☕ Accepts (state, element, downstream)
☕ Integrates element into state
• to update gatherer’s private state object
• to emit 0+ element(s) to downstream
Gatherers Components
Initializer (optional)
☕ Creates private state object
Combiner (optional)
☕ Can evaluate the gatherer in parallel
Finisher (optional)
☕ Accepts (state, downstream)
☕ Invoked when no more elements can be
consumed
☕ Emits element(s) to downstream
So You Want To Know More…
☕ Teaching Old Streams New Tricks (Devoxx Belgium 2023, Viktor Klang)
☕ Better Java Streams with Gatherers - Inside Java Newscast #57
Faster, Safer, Easier
Java-to-Native Interoperability
Project Panama
JNI and Reduced latency in G1GC
☕ JNI includes critical accessor functions.
☕ The JVM must not move a Java thread that is in a critical region
☕ Lock an object in place as the GC moves other objects (pinning).
Native Code
Functions
Libraries
JNI
GetPrimitiveArrayCritical
ReleasePrimitiveArrayCritical
Java Code
From Unsafe to proper handling
Create an object without
running its constructor
Directly access hardware
features or the CPU
Manually manage off-heap
memory
String payload = "22";
var functionName = "strlen";
Linker linker = Linker.nativeLinker();
SymbolLookup linkerLookup = linker.defaultLookup();
MemorySegment memSegment = linkerLookup.find(functionName).get();
FunctionDescriptor funcDescriptor = FunctionDescriptor.of(JAVA_INT, ADDRESS);
MethodHandle funcHandle = linker.downcallHandle(memSegment, funcDescriptor);
try (var arena = Arena.ofConfined()) {
var segment = arena.allocateFrom(payload);
int result = (int) funcHandle.invoke(segment);
System.out.println("The answer is " + result);
}
Foreign Function & Memory API
Get lookup object for string library
Get method handler for strlen
Invoke foreign function
Allocate the required foreign
memory
JExtract From Native C Headers
$ export C_INCLUDE_PATH=/Library/Developer/CommandLineTools/SDKs
$ jextract --output src -t org.unix -I $C_INCLUDE_PATH $C_INCLUDE_PATH/string.h
$ java --enable-native-access=ALL-UNNAMED --source FFMBenchmark.java
So You Want To Know More
☕ Evacuation Failure and Object Pinning
☕ Download jextract binaries
☕ Samples for jextract
☕ Learn how to write fast Java code with the Vector API - JEP Café #18
☕ Published content on Panama project: https://inside.java/tag/panama
Concurrent Programming without
Thread Leaks and Cancelation Delays
Project Loom
Virtual Threads Under the Hood
A thread managed
by JVM scheduler
can get a task
assigned by you.
Java scheduler
assigns the virtual
thread to platform
thread(s).
Virtual thread asks platform
thread(s) to perform the task.
If a virtual thread has some blocking
I/O operation, it will be detached from
the platform thread.
Another virtual thread is assigned to the
platform thread so that the platform thread
stays in a running state
Adoption
Structured Concurrency Advantages
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Present>()) {
var offer1 = scope.fork(() -> readOffer1(refPrice, boxPrice));
var offer2 = scope.fork(() -> readOffer2(refPrice, boxPrice));
var offer3 = scope.fork(() -> readOffer3(refPrice, boxPrice));
var offer4 = scope.fork(() -> readOffer4(refPrice, boxPrice));
scope.join();
Present quickPresent = scope.result();
return quickPresent;
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
Obtain a present fast from the available offers
☕ Create relationship between threads
☕ Forked tasks are children of the scope
☕ Success/failure policy can be defined across
all children.
Structured Concurrency Advantages
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Present>()) {
var offer1 = scope.fork(() -> readOffer1(refPrice, boxPrice));
var offer2 = scope.fork(() -> readOffer2(refPrice, boxPrice));
var offer3 = scope.fork(() -> readOffer3(refPrice, boxPrice));
var offer4 = scope.fork(() -> readOffer4(refPrice, boxPrice));
scope.join();
Present quickPresent = scope.result();
return quickPresent;
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
Obtain a present fast from the available offers
☕ Create relationship between threads
☕ Forked tasks are children of the scope
☕ Success/failure policy can be defined across
all children.
☕ Return the result of the first subtask that
completed with a result.
Structured Concurrency Advantages
try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Present>()) {
var offer1 = scope.fork(() -> readOffer1(refPrice, boxPrice));
var offer2 = scope.fork(() -> readOffer2(refPrice, boxPrice));
var offer3 = scope.fork(() -> readOffer3(refPrice, boxPrice));
var offer4 = scope.fork(() -> readOffer4(refPrice, boxPrice));
scope.join();
Present quickPresent = scope.result();
return quickPresent;
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
Obtain a present fast from the available offers
☕ Create relationship between threads
☕ Forked tasks are children of the scope
☕ Success/failure policy can be defined across
all children.
☕ Return the result of the first subtask that
completed with a result.
☕ Thread-dumps capture transparently the
relationship between threads.
Benefits for High Scaling Applications
Higher throughput with fewer CPU
operations when having high number
concurrent requests.
When having blocking calls, virtual threads
will go in a waiting state until they receive
data.
//in Wrapup record
ScopedValue.where(VALID_REQUEST, Choice.EXPERIENCE)
.call(() -> findOffer(data.itemPrice()));
// in Experience record
public Experience {
if (!VALID_REQUEST.isBound()) {
throw new IllegalStateException("not bound");
} else if (!VALID_REQUEST.get()
.equals(Choice.EXPERIENCE)) {
throw new
IllegalStateException(VALID_REQUEST.get());
}
}
//…
Experience Scoped Values
Find the best in price experience
☕ Best experience for a valid request
☕ Simplify reasoning about data flow
public static class ExperienceScope
extends StructuredTaskScope<Experience> {
//…
try (var scope = new Experience.ExperienceScope()) {
scope.fork(() -> readOffer1(referencePrice));
scope.fork(() -> readOffer2(referencePrice));
scope.fork(() -> readOffer3(referencePrice));
scope.fork(() -> readOffer4(referencePrice));
scope.join();
return scope.findOffer();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//…
Experience Scoped Values
Find the best in price experience
☕ Best experience for a valid request
☕ Simplify reasoning about data flow
☕ The lifetime of shared data is visible from
code structure.
☕ Data shared by a caller can be retrieved
only by legitimate callees.
☕ Performance through immutable shared
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
☕ JEP 464: Scoped Values (Second Preview)
Stay Tuned for More!
Inside.java
Dev.java youtube.com/java
Thank YOU!
Code

More Related Content

PDF
Java 21 Language Features and Beyond
PDF
Java 21 and Beyond- A Roadmap of Innovations
PDF
Java 23 and Beyond - A Roadmap Of Innovations
PPTX
Modern_Java_Workshop manjunath np hj slave
PDF
Java 25 and Beyond - A Roadmap of Innovations
PDF
JCConf 2021 - Java17: The Next LTS
PDF
JCConf 2020 - New Java Features Released in 2020
PPTX
Modern Java Workshop
Java 21 Language Features and Beyond
Java 21 and Beyond- A Roadmap of Innovations
Java 23 and Beyond - A Roadmap Of Innovations
Modern_Java_Workshop manjunath np hj slave
Java 25 and Beyond - A Roadmap of Innovations
JCConf 2021 - Java17: The Next LTS
JCConf 2020 - New Java Features Released in 2020
Modern Java Workshop

Similar to Java 22 and Beyond- A Roadmap of Innovations (20)

PPTX
Getting the Most From Modern Java
PPTX
Java 22_ Unwrapped: What You Need to Know.pptx
PPTX
Proposals for new function in Java SE 9 and beyond
PDF
core java
PPTX
The Art of Java Type Patterns
PPTX
Beyond java8
PDF
Java concepts and questions
DOCX
Jist of Java
DOCX
JAVA CONCEPTS AND PRACTICES
PDF
Java Full Throttle
PPTX
JDK 23_ Released and Ready – What’s Inside_.pptx
PPTX
Java9to19Final.pptx
PPTX
DevNexus 2020: Discover Modern Java
PPTX
Java Pattern Puzzles Java Pattern Puzzles
PPTX
Beginning Java for .NET developers
PPT
java training faridabad
PPT
Jug java7
PPT
Java Tutorials
PPTX
Core Java Tutorials by Mahika Tutorials
PDF
Exciting Features and Enhancements in Java 23 and 24
Getting the Most From Modern Java
Java 22_ Unwrapped: What You Need to Know.pptx
Proposals for new function in Java SE 9 and beyond
core java
The Art of Java Type Patterns
Beyond java8
Java concepts and questions
Jist of Java
JAVA CONCEPTS AND PRACTICES
Java Full Throttle
JDK 23_ Released and Ready – What’s Inside_.pptx
Java9to19Final.pptx
DevNexus 2020: Discover Modern Java
Java Pattern Puzzles Java Pattern Puzzles
Beginning Java for .NET developers
java training faridabad
Jug java7
Java Tutorials
Core Java Tutorials by Mahika Tutorials
Exciting Features and Enhancements in Java 23 and 24
Ad

More from Ana-Maria Mihalceanu (20)

PDF
Empower Inclusion Through Accessible Java Applications
PDF
Sécuriser les Applications Java Contre les Menaces Quantiques
PDF
Des joyaux de code natif aux trésors Java avec jextract
PDF
From native code gems to Java treasures with jextract
PDF
Monitoring Java Application Security with JDK Tools and JFR Events
PDF
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
PDF
From native code gems to Java treasures with jextract
PDF
Monitoring Java Application Security with JDK Tools and JFR Events
PDF
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
PDF
Monitoring Java Application Security with JDK Tools and JFR Events
PDF
Surveillance de la sécurité des applications Java avec les outils du JDK e...
PDF
A Glance At The Java Performance Toolbox
PDF
Monitoring Java Application Security with JDK Tools and JFR Events.pdf
PDF
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
PDF
From Java 17 to 21- A Showcase of JDK Security Enhancements
PDF
A Glance At The Java Performance Toolbox
PDF
A Glance At The Java Performance Toolbox.pdf
PDF
A Glance At The Java Performance Toolbox-TIA.pdf
PDF
A Glance At The Java Performance Toolbox.pdf
PDF
A Glance At The Java Performance Toolbox.pdf
Empower Inclusion Through Accessible Java Applications
Sécuriser les Applications Java Contre les Menaces Quantiques
Des joyaux de code natif aux trésors Java avec jextract
From native code gems to Java treasures with jextract
Monitoring Java Application Security with JDK Tools and JFR Events
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
From native code gems to Java treasures with jextract
Monitoring Java Application Security with JDK Tools and JFR Events
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
Monitoring Java Application Security with JDK Tools and JFR Events
Surveillance de la sécurité des applications Java avec les outils du JDK e...
A Glance At The Java Performance Toolbox
Monitoring Java Application Security with JDK Tools and JFR Events.pdf
Enhancing Productivity and Insight A Tour of JDK Tools Progress Beyond Java 17
From Java 17 to 21- A Showcase of JDK Security Enhancements
A Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox.pdf
A Glance At The Java Performance Toolbox-TIA.pdf
A Glance At The Java Performance Toolbox.pdf
A Glance At The Java Performance Toolbox.pdf
Ad

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Cloud computing and distributed systems.
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation theory and applications.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
cuic standard and advanced reporting.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Chapter 3 Spatial Domain Image Processing.pdf
Cloud computing and distributed systems.
MIND Revenue Release Quarter 2 2025 Press Release
MYSQL Presentation for SQL database connectivity
Encapsulation_ Review paper, used for researhc scholars
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Dropbox Q2 2025 Financial Results & Investor Presentation
Network Security Unit 5.pdf for BCA BBA.
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
The AUB Centre for AI in Media Proposal.docx
Encapsulation theory and applications.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Big Data Technologies - Introduction.pptx
Understanding_Digital_Forensics_Presentation.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
cuic standard and advanced reporting.pdf
Building Integrated photovoltaic BIPV_UPV.pdf

Java 22 and Beyond- A Roadmap of Innovations

  • 1. Java 22 and Beyond A Roadmap of Innovations
  • 2. Java Champion Alumni, Certified Architect Senior Developer Advocate at Oracle Passionate about solving complex scenarios involving Java and Kubernetes. ammbra1508.mastodon.social ammbra1508
  • 3. “The only way you can predict the future is to build it" Alan Kay Download and give it try: https://jdk.java.net/22/
  • 5. 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
  • 6. Java in the Small 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 things too • OOP concepts such as access control and static-ness should not overwhelm your first (or any small) program • The “on ramp" should lead smoothly onto the highway “Paving the On Ramp"
  • 8. Towards a Simplified Beginning // HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } Use jshell for fast prototyping Java code Launch via single file execution (since JDK 11) java HelloWorld.java
  • 9. Paving the On Ramp (in preview) // HelloWorld.java void main() { System.out.println("Hello, World!"); } JEP 463: Implicitly Declared Classes and Instance Main Methods (Second Preview) Class declaration no longer required main is not necessarily public static String[] args not declared if not used further
  • 10. Invocation Order when Selecting Main ☕ A static void main(String[] args) method of non-private access in the launched class. ☕ A static void main() method with non-private access in the launched class. ☕ A non-private void main(String[] args) instance method in the launched class/inherited from a superclass. ☕ A non-private void main() instance method in the launched class or inherited from a superclass.
  • 11. One Command to Launch Them All // HelloWorld.java class HelloWorld { void main() { Helper.run(); } } ◦ // Helper.java import static java.lang.System.out; class Helper { static void run() { out.println("Hello World!"); } } JEP 458: Launch Multi-File Source-Code Programs java --enable-preview --source 22 HelloWorld.java
  • 12. So you want to know more… ☕ JEP 463: Implicitly Declared Classes and Instance Main Methods (Second Preview) ☕ Script Java Easily in 21 and Beyond - Inside Java Newscast #49 ☕ JEP 458: Launch Multi-File Source-Code Programs ☕ Does Java 22 Kill Build Tools? - Inside Java Newscast #63 ☕ JEP 477: Implicitly Declared Classes and Instance Main Methods (Third Preview)
  • 13. Thoughtful Evolution of Java Language Features Project Amber
  • 14. Wrapup Data Modeling ☕ A sender can do a nice gesture and offer a gift. ☕ A gift can only be either a postcard or add to it one of the following: an online coupon, buy an experience or a material present. ☕ A postcard does not have an associated cost, all the other 3 types of products have a price. ☕ A sender can never send 2 postcards as a gift. ☕ An online coupon has an expiry date. ☕ A present can be placed inside a box. ☕ A coupon could be bought for sharing an experience too.
  • 15. Wrapup Data Modeling Detailed ☕ Sealed types limit which subtypes can directly extend/implement them. public sealed interface Intention permits Coupon, Experience, Present, Postcard {} public sealed class Experience implements Intention permits Coupon {} ☕ Present,Postcard are records. ☕ Coupon extends Experience. ☕ Represent Gift using composite patterns.
  • 16. Inheritance and Constructor Chaining public final class Coupon extends Experience implements Intention { private final LocalDate expiringOn; public Coupon(double price, LocalDate expiringOn, Currency currency) { super(verifyPositive(price), currency); this.expiringOn = expiringOn; } private static double verifyPositive(double price) { if (price < 0) { throw new IllegalArgumentException("Price cannot be negative"); } return price; } } Constructor chaining is enforced in subclass.
  • 17. Statements Before super(…) (in preview) public final class Coupon extends Experience implements Intention { private final LocalDate expiringOn; public Coupon(double price, LocalDate expiringOn, Currency currency) { if (price < 0) { throw new IllegalArgumentException("Price cannot be negative"); } super(price, currency); this.expiringOn = expiringOn; } } JEP 447: Statements before super(...) (Preview) Validate superclass constructor arguments Prepare superclass constructor arguments Share superclass constructor arguments
  • 18. Wrapup Expressive Data Modeling ☕ Sealed types limit which subtypes can directly extend/implement them. public sealed interface Intention permits Coupon, Experience, Present, Postcard { //… } ☕ Coupon,Experience,Present,Postcard are records. ☕ Represent Gift using nested record patterns.
  • 19. Record Patterns and Exhaustive Switch JSONObject process(Gift gift, Choice choice) { return switch (gift) { case Gift(Postcard p, Postcard p2) -> new JSONObject(p); case Gift(Postcard p, Coupon c) when (c.price() == 0.0) -> new JSONObject(p); case Gift(Postcard p, Experience e) when (e.price() == 0.0) -> new JSONObject(p); case Gift(Postcard p, Present pr) when (pr.itemPrice() == 0.0) -> new JSONObject(p); case Gift(Postcard p, Experience e) -> gift.merge(choice.name().toLowerCase()); case Gift(Postcard p, Present pr) -> gift.merge(choice.name().toLowerCase()); case Gift(Postcard p, Coupon c) -> gift.merge(choice.name().toLowerCase()); }; }
  • 20. Code Readability and Lower Error Chances JSONObject process(Gift gift, Choice choice) { return switch (gift) { case Gift(Postcard p, Postcard _) -> new JSONObject(p); case Gift(Postcard p, Coupon c) when (c.price() == 0.0) -> new JSONObject(p); case Gift(Postcard p, Experience e) when (e.price() == 0.0) -> new JSONObject(p); case Gift(Postcard p, Present pr) when (pr.itemPrice() == 0.0) -> new JSONObject(p); case Gift(_, Coupon _), Gift(_, Experience _), Gift(_, Present _) -> { String option = choice.name().toLowerCase(); yield gift.merge(option); } }; } JEP 456: Unnamed Variables & Patterns
  • 21. So You Want To Know More… ☕ 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
  • 22. Fundamental Changes to Achieve Your Application Goals Core Libraries
  • 23. Compiling and Launching a Java Program IDE javac java .java source file bytecode .class file Program running
  • 25. 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 457: Class-File API (Preview)
  • 26. So You Want To Know More… ☕ A Classfile API for the JDK (JVMLS 2023, Brian Goetz) ☕ New Class-File API will make Java Updates easier - Inside Java Newscast #56
  • 27. 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; IntStream.range(0, (letters.size() + size - 1) / size) .mapToObj(i -> String.join("", letters.subList(i * size, Math.min(size * (i + 1), letters.size())))) .toList(); // ABC // DEF // GH ☕ Some intermediate operations are missing: sliding windows, take-while-including, fixed grouping, scanning, etc.
  • 28. 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 461: Stream Gatherers (Preview)
  • 29. Integrator (mandatory) ☕ Accepts (state, element, downstream) ☕ Integrates element into state • to update gatherer’s private state object • to emit 0+ element(s) to downstream Gatherers Components Initializer (optional) ☕ Creates private state object Combiner (optional) ☕ Can evaluate the gatherer in parallel Finisher (optional) ☕ Accepts (state, downstream) ☕ Invoked when no more elements can be consumed ☕ Emits element(s) to downstream
  • 30. So You Want To Know More… ☕ Teaching Old Streams New Tricks (Devoxx Belgium 2023, Viktor Klang) ☕ Better Java Streams with Gatherers - Inside Java Newscast #57
  • 31. Faster, Safer, Easier Java-to-Native Interoperability Project Panama
  • 32. JNI and Reduced latency in G1GC ☕ JNI includes critical accessor functions. ☕ The JVM must not move a Java thread that is in a critical region ☕ Lock an object in place as the GC moves other objects (pinning). Native Code Functions Libraries JNI GetPrimitiveArrayCritical ReleasePrimitiveArrayCritical Java Code
  • 33. From Unsafe to proper handling Create an object without running its constructor Directly access hardware features or the CPU Manually manage off-heap memory
  • 34. String payload = "22"; var functionName = "strlen"; Linker linker = Linker.nativeLinker(); SymbolLookup linkerLookup = linker.defaultLookup(); MemorySegment memSegment = linkerLookup.find(functionName).get(); FunctionDescriptor funcDescriptor = FunctionDescriptor.of(JAVA_INT, ADDRESS); MethodHandle funcHandle = linker.downcallHandle(memSegment, funcDescriptor); try (var arena = Arena.ofConfined()) { var segment = arena.allocateFrom(payload); int result = (int) funcHandle.invoke(segment); System.out.println("The answer is " + result); } Foreign Function & Memory API Get lookup object for string library Get method handler for strlen Invoke foreign function Allocate the required foreign memory
  • 35. JExtract From Native C Headers $ export C_INCLUDE_PATH=/Library/Developer/CommandLineTools/SDKs $ jextract --output src -t org.unix -I $C_INCLUDE_PATH $C_INCLUDE_PATH/string.h $ java --enable-native-access=ALL-UNNAMED --source FFMBenchmark.java
  • 36. So You Want To Know More ☕ Evacuation Failure and Object Pinning ☕ Download jextract binaries ☕ Samples for jextract ☕ Learn how to write fast Java code with the Vector API - JEP Café #18 ☕ Published content on Panama project: https://inside.java/tag/panama
  • 37. Concurrent Programming without Thread Leaks and Cancelation Delays Project Loom
  • 38. Virtual Threads Under the Hood A thread managed by JVM scheduler can get a task assigned by you. Java scheduler assigns the virtual thread to platform thread(s). Virtual thread asks platform thread(s) to perform the task. If a virtual thread has some blocking I/O operation, it will be detached from the platform thread. Another virtual thread is assigned to the platform thread so that the platform thread stays in a running state
  • 40. Structured Concurrency Advantages try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Present>()) { var offer1 = scope.fork(() -> readOffer1(refPrice, boxPrice)); var offer2 = scope.fork(() -> readOffer2(refPrice, boxPrice)); var offer3 = scope.fork(() -> readOffer3(refPrice, boxPrice)); var offer4 = scope.fork(() -> readOffer4(refPrice, boxPrice)); scope.join(); Present quickPresent = scope.result(); return quickPresent; } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } Obtain a present fast from the available offers ☕ Create relationship between threads ☕ Forked tasks are children of the scope ☕ Success/failure policy can be defined across all children.
  • 41. Structured Concurrency Advantages try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Present>()) { var offer1 = scope.fork(() -> readOffer1(refPrice, boxPrice)); var offer2 = scope.fork(() -> readOffer2(refPrice, boxPrice)); var offer3 = scope.fork(() -> readOffer3(refPrice, boxPrice)); var offer4 = scope.fork(() -> readOffer4(refPrice, boxPrice)); scope.join(); Present quickPresent = scope.result(); return quickPresent; } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } Obtain a present fast from the available offers ☕ Create relationship between threads ☕ Forked tasks are children of the scope ☕ Success/failure policy can be defined across all children. ☕ Return the result of the first subtask that completed with a result.
  • 42. Structured Concurrency Advantages try (var scope = new StructuredTaskScope.ShutdownOnSuccess<Present>()) { var offer1 = scope.fork(() -> readOffer1(refPrice, boxPrice)); var offer2 = scope.fork(() -> readOffer2(refPrice, boxPrice)); var offer3 = scope.fork(() -> readOffer3(refPrice, boxPrice)); var offer4 = scope.fork(() -> readOffer4(refPrice, boxPrice)); scope.join(); Present quickPresent = scope.result(); return quickPresent; } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } Obtain a present fast from the available offers ☕ Create relationship between threads ☕ Forked tasks are children of the scope ☕ Success/failure policy can be defined across all children. ☕ Return the result of the first subtask that completed with a result. ☕ Thread-dumps capture transparently the relationship between threads.
  • 43. Benefits for High Scaling Applications Higher throughput with fewer CPU operations when having high number concurrent requests. When having blocking calls, virtual threads will go in a waiting state until they receive data.
  • 44. //in Wrapup record ScopedValue.where(VALID_REQUEST, Choice.EXPERIENCE) .call(() -> findOffer(data.itemPrice())); // in Experience record public Experience { if (!VALID_REQUEST.isBound()) { throw new IllegalStateException("not bound"); } else if (!VALID_REQUEST.get() .equals(Choice.EXPERIENCE)) { throw new IllegalStateException(VALID_REQUEST.get()); } } //… Experience Scoped Values Find the best in price experience ☕ Best experience for a valid request ☕ Simplify reasoning about data flow
  • 45. public static class ExperienceScope extends StructuredTaskScope<Experience> { //… try (var scope = new Experience.ExperienceScope()) { scope.fork(() -> readOffer1(referencePrice)); scope.fork(() -> readOffer2(referencePrice)); scope.fork(() -> readOffer3(referencePrice)); scope.fork(() -> readOffer4(referencePrice)); scope.join(); return scope.findOffer(); } catch (InterruptedException e) { throw new RuntimeException(e); } //… Experience Scoped Values Find the best in price experience ☕ Best experience for a valid request ☕ Simplify reasoning about data flow ☕ The lifetime of shared data is visible from code structure. ☕ Data shared by a caller can be retrieved only by legitimate callees. ☕ Performance through immutable shared data.
  • 46. 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 ☕ JEP 464: Scoped Values (Second Preview)
  • 47. Stay Tuned for More! Inside.java Dev.java youtube.com/java