Modern Java 21+
The Next-Level Upgrade
GitHub Repository
Java Latest
https://github.com/kousen/java_latest
Documentation pages
https://docs.oracle.com/en/java/javase/21/ (replace 21 with any other version)
- Tools Reference
- JShell User Guide
- Javadoc Guide
Note: Actual API Javadocs are at:
https://docs.oracle.com/en/java/javase/21/docs/api/index.html
Java Licensing Is a Mess, But...
Java is Still Free 3.0.0 - Java Champions
Java 8
End of life without commercial support (ended Jan 2019)
Open JDK (and others) still provide updates
Java 11+
Oracle JDK requires license for production use
Open JDK (and others) are free
JDK Proposals
You can see which JEPs (Java Enhancement Proposals) in which version:
http://openjdk.org/projects/jdk/
Click on the JDK version number to see what was included in each
Collection Factory Methods (JDK 9)
List.of, Set.of, Map.of, Map.ofEntries
Collection Factory Methods
List.of(a, b, b, c, ...)
Set.of(a, b, c, ...)
Map.of(k1, v1, k2, v2, k3, v3, ...)
Map.ofEntries(
Map.entry(k1, v1),
Map.entry(k2, v2),
Map.entry(k3, v3), …)
Collection Factory Methods
What to remember:
No nulls
Produces unmodifiable collections
Set.of does not allow duplicates
Local Variable Type Inference
(JDK 10 and 11)
The var reserved type name
var Data Type
Local variables only
- No fields
- No method parameters
- No method return types
var is a "reserved type name", not a keyword (can still have variable called "var")
Can also use on
- for loops
- try-with-resources blocks
var Data Type
Stuart Marks: Style Guidelines for Local Variable Type Inference in Java
https://openjdk.org/projects/amber/guides/lvti-style-guide
Local variables only
HTTP Client (JDK 11)
Built-in sync and async networking
HTTP 2 Client
New HTTP Client API
Supports HTTP/2 and websockets
Replaces HttpURLConnection
Both synchronous and asynchronous modes
JShell (JDK 9)
The Java REPL
JShell
Java interpreter
https://docs.oracle.com/en/java/javase/17/jshell/introduction-jshell.html
> jshell (or add -v for verbose)
jshell>
/exit to leave
No semicolons needed
Single File Code Execution (JDK 11)
Run without explicit compilation
Single File Code Execution
- Run source code from command line
- java HelloWorld.java
- Compiles, but doesn't save compiled class
- First top-level class in file is executed
- Must contain a standard main method
- Can make "script" using shebang notation, #!
- Make file executable, then add this line:
- #!/path/to/java --source version
Enhanced Switch Statement
(JDK 14)
Makes switch useable
Enhanced Switch
- Expressions return a value
- Arrow rather than colon, so no fall through
- Multiple case labels
- Statement blocks use yield to return from block only
- Must be exhaustive
Text Blocks (JDK 15)
Multiline Strings
Text Blocks
- Use "triple double" quotes (""") and a newline
- Indentation based on closing """
- stripIndent, indent, translateEscapes
Records (JDK16)
Data classes
Records
- Intended to hold data
- Add attributes using constructor syntax
- generates getter methods (but not following the convention!)
- final
- extends java.lang.Record
- generates toString, equals, and hashCode
- can add static fields
Pattern Matching
For instanceof (JDK 16)
For switch (JDK 21)
For records (JDK 21)
Pattern matching
- Enhances the instanceof operator
- if (shape instanceof Square s) → use square methods on s
- Like a "smart cast"
See also "Java Feature Spotlight: Pattern Matching"
by Brian Goetz in InfoQ
https://www.infoq.com/articles/java-pattern-matching/
Pattern Matching for switch
from JEP 406:
Sealed Classes (JDK 17)
Restricted type hierarchies
Sealed Classes (JDK 17)
- Sealed classes (or interfaces!) can only be extended by permission
- Use sealed modifier
- Use permits clause for subclasses
- Use non-sealed to open up children
- First ever Java keyword with a hyphen :)
- Children are open unless final
- All classes must be in the same module
- If unnamed module, same package
Sealed classes
Simple Web Server (JDK 18)
Trivial web server
Simple Web Server (JDK 18)
- jwebserver
- Alias for java -m jdk.httpserver
- Runs on port 8000 (change with -p flag)
- Supports GET and HEAD requests only
- No https
- Supports HTTP/1.1 only
- Serves files and folder listings only
- See details in com.sun.net.httpserver package
Deprecated Annotation
@Deprecated now has fields:
- forRemoval
- since
Tool jdeprscan to scan a jar file for deprecated uses
See also The Java Version Almanac
- Lets you compare the Java API between any two versions
Sequenced Collections (JDK 21)
Easy access to first and last elements
Sequenced Collections
● https://openjdk.org/jeps/431
● New methods in interface (promoted from Deque)
○ addFirst(), addLast()
○ getFirst(), getLast()
○ removeFirst(), removeLast()
○ reversed() → reverses ordering
● SequencedSet: just reversed()
● SequencedMap:
○ Similar methods → see JEP for details
Virtual Threads (JDK 21)
"Unlimited" threads
Virtual Threads
● https://openjdk.org/jeps/444
● Threads are no longer tied to platform threads
● Virtual threads should never be pooled
● Executors.newVirtualThreadPerTaskExecutor()
● Thread.ofPlatform().name(...), Thread.ofVirtual().name(...)
● Use when:
○ Number of concurrent tasks is high (more than a few thousand)
○ Workload is not CPU bound
Data-Oriented Programming
● An approach to software development that emphasizes
the separation of data and behavior
● Operations are kept separate from data structures
● Transformations are used on the data
● Immutability is encouraged
● Functional processing with streams
Data-Oriented Programming
● Advantages:
○ Performance
○ Simplicity and Maintainability
○ Concurrency (immutable objects)
○ Testability (stateless functions)
D.O.P. in Java
● Java 21 has everything you need
○ Records for the data structures
○ Sealed interfaces to limit the types to only what you need
○ Pattern matching for switch for the behavior
● See the "astro" example in the GitHub repository
● Also see article by Brian Goetz, Data Oriented Programming in Java,
https://www.infoq.com/articles/data-oriented-programming-java/
The Module System (JDK 9)
The Good and Bad of JPMS
JPMS
Module descriptors
module-info.java
exports, requires, uses, …
Quick start guide:
https://openjdk.org/projects/jigsaw/quick-start
State of the Module System
https://openjdk.org/projects/jigsaw/spec/sotms/
JPMS
module name → use "reverse dns" (like packages)
requires → add a module to the "module path"
java.base added automatically
transitive → any package using this module can read the arg
exports → list of packages exported by a module
can export to selected modules
Modularization Benefits
- True encapsulation
- Smaller libraries using only needed modules
- jlink on JDK
- Ordering dependencies on the module path
Is that worth changing the fundamental meaning of public and private?
- If you are making a library, maybe
- If you're not, probably not
Summary
- Need to know functional features
- Streams with map / filter / reduce
- Lambda expressions
- Method references
- Concurrent, parallel streams
- Need to use Optional
- See also Should I Upgrade My Java GitHub repo for performance tests
- Helpful to know preview features
- Enhanced switch
- Text blocks
- Records
- Pattern matching
- Can probably ignore modules (unless you're a library developer)
Contact Info
Ken Kousen
Kousen IT, Inc.
ken.kousen@kousenit.com
http://www.kousenit.com
https://kousenit.org (blog)
@kenkousen (twitter)
https://foojay.social/@kenkousen (mastodon)
Tales from the jar side (free newsletter)
https://kenkousen.substack.com
https://youtube.com/@talesfromthejarside