Modern Java 21+
The Next-Level Upgrade
GitHub Repository
Java Latest
[Link]
Documentation pages
[Link] (replace 21 with any other version)
- Tools Reference
- JShell User Guide
- Javadoc Guide
Note: Actual API Javadocs are at:
[Link]
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:
[Link]
Click on the JDK version number to see what was included in each
Collection Factory Methods (JDK 9)
[Link], [Link], [Link], [Link]
Collection Factory Methods
[Link](a, b, b, c, ...)
[Link](a, b, c, ...)
[Link](k1, v1, k2, v2, k3, v3, ...)
[Link](
[Link](k1, v1),
[Link](k2, v2),
[Link](k3, v3), …)
Collection Factory Methods
What to remember:
No nulls
Produces unmodifiable collections
[Link] 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
[Link]
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
[Link]
> 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 [Link]
- 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 [Link]
- 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
[Link]
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 [Link]
- 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 [Link] 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
● [Link]
● 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
● [Link]
● Threads are no longer tied to platform threads
● Virtual threads should never be pooled
● [Link]()
● [Link]().name(...), [Link]().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,
[Link]
The Module System (JDK 9)
The Good and Bad of JPMS
JPMS
Module descriptors
[Link]
exports, requires, uses, …
Quick start guide:
[Link]
State of the Module System
[Link]
JPMS
module name → use "reverse dns" (like packages)
requires → add a module to the "module path"
[Link] 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.
[Link]@[Link]
[Link]
[Link] (blog)
@kenkousen (twitter)
[Link] (mastodon)
Tales from the jar side (free newsletter)
[Link]
[Link]