Markus Günther
Freelance Software Engineer / Architect
mail@mguenther.net | mguenther.net | @markus_guenther
Java
A Journey Through the JDKs
2
A brief history of recent Java versions
Version Release End Of Life
Java 8 (LTS) 2014.03 2030.12
Java 9 2017.09 2018.03*
Java 10 2018.03 2018.09*
Java 11 (LTS) 2018.09 2027.09
Java 12 2019.03 2019.09*
Java 13 2019.09 2020.03*
Java 14 2020.03 2020.09*
Java 15 2020.09 2021.03*
Java 16 2021.03 2021.09*
Java 17 (LTS) 2021.09 TBA
3
Disclaimer
General ▪ Covers noteworthy features from a developer‘s perspective
▪ Selection is 100% opinionated
Early Access ▪ Experimental: Alpha release, activated by flag
▪ Incubator Module: Beta release, separate module underneath jdk.incubator
▪ Preview Feature: Release candidate
▪ Mostly feature complete, semi-stable API, not production-ready
Release Highlight Quality of Life
Improvement
New (Language)
Feature
4
Java 9
5
Java 9 features the following JEPs.
JEP Title JEP Title
102 Process API Updates 214 Remove GC Combinations Deprecated in JDK 8
110 HTTP 2 Client 215 Tiered Attribution for javac
143 Improve Contended Locking 216 Process Import Statements Correctly
158 Unified JVM Logging 217 Annotations Pipeline 2.0
165 Compiler Control 219 Datagram Transport Layer Security (DTLS)
193 Variable Handles 220 Modular Run-Time Images
197 Segmented Code Cache 221 Simplified Doclet API
199 Smart Java Compilation, Phase Two 222 jshell: The Java Shell (Read-Eval-Print-Loop)
200 The Modular JDK 223 New Version-String Scheme
201 Modular Source Code 224 HTML5 Javadoc
211 Elide Deprecation Warnings on Import Stmts. 225 Javadoc Search
212 Resolve Lint and Doclint Warnings 226 UTF-8 Property Files
213 Milling Project Coin 227 Unicode 7.0
6
Java 9 features the following JEPs. (cont.)
JEP Title JEP Title
228 Add More Diagnostic Commands 245 Validate JVM Command-Line Flag Arguments
229 Create PKC512 Keystores by Default 246 Leverage CPU Instructions for GHASH and RSA
231 Remove Launch-Time JRE Version Selection 247 Compile for Older Platform Versions
232 Improve Secure Application Performance 248 Make G1 the Default Garbage Collector
233 Generate Runtime Compiler Tests Automatically 249 OCSP Stapling for TLS
235 Test Class-File Attributes Gen. by javac 250 Store Interned Strings in CDS Archives
236 Parser API for Nashorn 251 Multi-Resolution Images
237 Linux/AArch64 Port 252 Use CLDR Locale Data by Default
238 Multi-Release JAR Files 253 Prepare JavaFX UI Controls for Modularization
240 Remove the JVM TI hprof Agent Prepare JavaFX CSS APIs for Modularization
241 Remove the jhat Tool 254 Compact Strings
243 Java-Level JVM Compiler Interface 255 Merge Selected Xerces 2.11.0 Updates into JAXP
244 TLS Application-Layer Protocol Negotiation Ext. 256 BeanInfo Annotations
7
Java 9 features the following JEPs. (cont.)
JEP Title JEP Title
257 Update JavaFX/Media to New Ver. of Gstreamer 270 Reserved Stack Areas for Critical Sections
258 HarfBuzz Font-Layout Engine 271 Unified GC Logging
259 Stack-Walking API 272 Platform-Specific Desktop Features
260 Encapsulate Most Internal APIs 273 DRGB-Based SecureRandom Implementations
261 Module System 274 Enhanced Method Handles
262 TIFF Image I/O 275 Modular Java Application Packaging
263 HiDPI Graphics on Windows and Linux 276 Dynamic Linking of Language-Defined Obj. Models
264 Platform Logging API and Service 277 Enhanced Deprecation
265 Marlin Graphics Renderer 278 Additional Tests for Humongous Objects in G1
266 More Concurrency Updates 279 Improve Test-Failure Troubleshooting
267 Unicode 8.0 280 Indify String Concatenation
268 XML Catalogs 281 HotSpot C++ Unit-Test Framework
269 Convenience Factory Methods for Collections 282 jlink: The Java Linker
8
Java 9 features the following JEPs. (cont.)
JEP Title JEP Title
283 Enable GTK 3 on Linux 299 Reorganize Documentation
284 New HotSpot Build System
285 Spin-Wait Hints
287 SHA-3 Hash Algorithms
288 Disable SHA-1 Certificates
289 Deprecate the Applet API
290 Filter Incoming Serialization Data
291 Deprecate the CMS Garbage Collector
292 Implement Sel. ECMAScript 6 Feat. in Nashorn
294 Linux/s390x Port
295 Ahead-of-Time Compilation
297 Unified arm32/arm64 Port
298 Remove Demos and Samples
9
Java 9 includes 91 JEPs. The most noteworthy for developers are
based around modularization and API enhancements.
JEPs ▪ The Java Platform Module System (JPMS)
▪ jshell: A read-eval-print-loop for Java (REPL)
▪ Private methods in interfaces
▪ Convenient factory methods for collections
▪ Couple of small language and API enhancements
▪ ...
1
The Java Platform Module System brings modules as first-class-
citizens to Java.
History ▪ JSR 376: Java Platform Module System (JPMS)
▪ also known as Project Jigsaw
▪ Closes around a couple of JEPs
▪ the module system itself (JEP 261)
▪ the modular JDK (JEP 200, JEP 201, JEP 220)
▪ encapsulation of internal APIs (JEP 260)
▪ toolchain – jlink (JEP 282)
Why? ▪ Strong Encapsulation
▪ Reliable Configuration
▪ Scalable Java SE Platform
1
The Java Platform Module System allows us to hide
implementation details.
module timetracking.invoice
package
timetracking.invoice.impl
package
timetracking.invoice.api
module timetracking.client
package
timetracking.client
module timetracking.invoice {
exports timetracking.invoice.api;
}
module-info.java
module timetracking.client {
requires timetracking.invoice;
}
module-info.java
1
Think holistically when transforming the architectural blueprint
into the application architecture.
Classes Application
?
Design considerations and architectural tasks percolate through every layer
▪ Classes are easy to access and use within the code base
▪ ... but classes are no deployment artifacts!
▪ Expose a class as a service?
▪ Copy a class over to another application?
1
Classes are too fine-grained to be used as the single
organizational unit of a large code base.
▪ Group classes into packages
▪ Allows us to reason about design on a higher level of abstraction
▪ How to group things together?
Classes Packages Application
?
Design considerations and architectural tasks percolate through every layer
1
Packages can provide the required organizational trait, but are
no deployment artifacts.
Modules ...
▪ ... can be installed, uninstalled, updated
▪ ... are composable and testable units of deployment
▪ ... can be re-used inside a process
Classes Packages Application
?
Design considerations and architectural tasks percolate through every layer
Modules
1
A holistic view on the architecture of an application shows that
there are more artifacts at play to provide a proper structure.
Classes Packages Modules Application
State Deployment and Management
Composition and Test
Interprocess Reuse
Intraprocess Reuse
1
A holistic view on the architecture of an application shows that
there are more artifacts at play to provide a proper structure.
SOA Principles &
Patterns
Modularity Patterns
Package Design
Principles & Patterns
Quality of Code,
Design Patterns,
SOLID
Packages Modules Application
Classes
Design considerations and architectural tasks percolate through every layer
1
The Java Platform Module System does not satisfy all
requirements for a runtime module system.
Strong En-
capsulation
▪ public classes are visible to all classes in the classpath
▪ It is not possible to hide implementation details
➔ A module system allows to hide implementation details.
Dynamic
Deployment
▪ Updating a software means re-starting the JVM that runs it
➔ A module system supports hot deployment.
➔ JPMS does not support that.
Versioning ▪ Java does not allow to version classes / packages.
▪ What about state migrations?
➔ A module system supports versioning of code artefacts.
➔ JPMS does not support that.
Dependency
Management
▪ Java does not allow to manage dependencies.
▪ Tools like Maven solve that problem ...
▪ ... but not a runtime!
➔ A module system supports dependency management at runtime.
➔ JPMS does not support that.
1
The Java Platform Module System: The good, the bad, the ugly.
What’s to like and what not?
• A long overdue step towards true
software components.
• Aggregator modules allow grouping of
modules via requires transitive.
PRAISE
• public no longer means that a class is
accessible.
• The JPMS does not support versioned
modules natively, but only informally.
• Split-Packages: Why, just why?
• There is only one scope.
• No wildcard support when exporting
packages.
SHAME
1
The JPMS enables us to apply a vast variety of modularity
patterns. Want to know more?
Books ▪ Knoernschild K., Java Application Architecture: Modularity Patterns with Examples
Using OSGi, Robert C. Martin Series, Prentice Hall (1st Edition), 03/2012
▪ Mak S. and Bakker P., Java 9 Modularity: Patterns and Practices for Developing
Maintainable Applications, O‘Reilly, 09/2017
Articles ▪ Günther M., Der Weg zu einer modularisierten Java-Anwendung, JavaMagazin,
03/2019, p. 10-18
▪ Günther M., A Journey to Java 9 Modules (blog series),
https://www.mguenther.net/tag/modularity.html, 01/2018
2
Milling Project Coin (JEP 213) comprises a couple of features wrt.
syntactical enhancements.
Features ▪ private methods in interfaces
▪ try-with-resources for effectively final AutoCloseables
▪ Anonymous Diamond Operator
▪ @SafeVarargs for Generics and Variable Argument Lists
▪ Underscore is no longer treated as an admissible identifier
class X<T> {}
X<?> x = new X<>(){}; // X<> is admissible since Java 9
@SafeVarargs
private int lengthOf(List<String>... list) {
List<String>[] l = list;
return l.length;
}
2
Using private methods in interfaces allows us to break apart
default methods into smaller units.
public interface UserService {
boolean isAllowed(User user, Right right);
default List<Right> getRights(User user) {
List<Right> userRights = new ArrayList();
user.getRoles().forEach((Role role) -> {
userRights.addAll(role.getRights());
});
return userRights;
}
}
A sample interface that uses a default method (Java 8)
2
Using private methods in interfaces allows us to break apart
default methods into smaller units. (cont.)
public interface UserService {
boolean isAllowed(User user, Right right);
default List<Right> getRights(User user) {
List<Right> userRights = new ArrayList();
addAllUserRights(user, userRights);
return userRights;
}
private void addAllUserRights(User user, List<Right> userRights) {
user.getRoles().forEach((Role role) -> {
userRights.addAll(role.getRights());
});
}
}
Using a private method to structure the interface implementation (Java 9)
2
AutoCloseable resources must not be initialized with the try-
block. They are closed automatically if they are effectively final.
try (MyCloseableResource resource = new MyCloseableResource()) {
...
}
try-with-resources prior to Java 9
MyCloseableResource resource = new MyCloseableResource();
try (resource) {
...
}
try-with-resources since Java 9
2
JEP 277 brings a couple of small changes to Java’s deprecation
mechanism.
Features ▪ Attribute @Deprecated with properties
▪ since: The version in which the annotated class or method got deprecated
▪ forRemoval: Whether the class or method will be removed in a future release
▪ No longer shows deprecation warning on import
@Deprecated(since="9", forRemoval=true)
class NoLongerUsed {}
class Main {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
NoLongerUsed unused = new NoLongerUsed();
}
}
2
Optional<T> supports a couple of new methods.
Methods ▪ void ifPresentOrElse(Consumer<? super T>, Runnable)
▪ Optional<T> or(Supplier<? extends Optional<? extends T>>)
Optional<Customer> c = findCustomer(customerId);
c.ifPresentOrElse(customer -> onCustomerFound(customer),
() -> onMissingCustomer());
Optional<Customer> = findInCache(customerId)
.or(() -> findInDatabase(customerId))
2
Optional<T> supports a couple of new methods. (cont.)
Methods ▪ Stream<T> stream()
Stream<Optional<String>> optGhostbusters = Stream.of(
Optional.of("Peter"),
Optional.of("Ray"),
Optional.empty(),
Optional.of("Egon"),
Optional.empty(),
Optional.of("Winston"));
Stream<String> ghostbusters = optGhostbusters
.flatMap(Optional::stream);
2
Stream<T> supports a couple of new methods.
Methods ▪ Stream<T> takeWhile(Predicate<? super T> predicate)
▪ Stream<T> dropWhile(Predicate<? super T> predicate)
Stream
.iterate(0, i -> i + 1)
.takeWhile(n -> n < 10)
.forEach(System.out::println);
Terminate an infinite stream if a condition no longer holds
Stream
.of(5, 8, 12, 16, 51)
.dropWhile(n -> n < 10)
.forEach(System.out::println);
Discard elements as long as a condition holds
2
Stream<T> supports a couple of new methods. (cont.)
Methods ▪ Stream<T> ofNullable(T t)
collection.stream()
.flatMap(s -> {
Integer t = map.get(s);
return t != null ? Stream.of(t) : Stream.empty();
})
.collect(Collectors.toList());
Handling null values inside a Stream<T> is cumbersome
collection.stream()
.flatMap(s -> Stream.ofNullable(map.get(s)))
.collect(Collectors.toList());
Apply ofNullable(T t) to remove boilerplate code
2
Stream<T> supports a couple of new methods. (cont.)
Methods ▪ Stream<T> iterate(T seed,
Predicate<? super T> hasNext,
UnaryOperator<T> next)
Stream
.iterate(0, n -> n < 10, i -> i + 1)
.forEach(System.out::println);
3
JEP 269 features enhances the Java Collection API by adding
factory methods for the construction of immutable collections.
List ▪ List<E> of()
▪ List<E> of(E e1)
▪ ...
List<String> l = List.of("a", "b", "c");
Set ▪ Set<E> of()
▪ Set<E> of(E e1)
▪ ...
Set<String> s = Set.of("a", "b", "c");
3
JEP 269 features enhances the Java Collection API by adding
factory methods for the construction of immutable collections.
Map ▪ Map<K,V> of()
▪ Map<K,V> of(K k1, V v1)
▪ Map<K,V> of(K k1, V v1, K k2, V v2)
▪ ...
Map<String, Integer> m = Map.of(
"a", 1,
"b", 2,
"c", 3);
3
JEP 266 (More Concurrency Updates) most notably introduces a
lean API for reactive streams to Java.
Publisher Subscriber
Subscription
subscribe
creates
subscription
notifies
subscriber
pushes
data
3
Subscriber<T> defines a lean interface that let’s us implement
the receiving end of a reactive stream.
class Sink<T> implements Flow.Subscriber<T> {
private Flow.Subscription subscription;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(T item) {
/* Process item, then request next item(s) */
subscription.request(1);
}
@Override public void onError(Throwable t) { ... }
@Override public void onComplete() { ... }
}
Simple data sink that is on the receiving end of a reactive stream
3
A SubmissionPublisher<T> is a Flow.Publisher<T> that
implements the asynchronous heavy-lifting for us.
Sink<String> sink = new Sink<>();
SubmissionPublisher<String> publisher = new SubmissionPublisher<>();
publisher.subscribe(subscriber);
List
.of("a", "b", "c", "d", "e", "f")
.forEach(publisher::submit);
publisher.close();
Subscribe the data sink to the publisher
3
A Processor<T,R> is a Subscriber<T> and a Publisher<R>,
which allows us to build complex reactive processing chains.
Publisher Subscriber
Subscription
Processor
Subscription
subscribe subscribe
3
Compact Strings (JEP 254) improves the memory consumption of
Strings.
History ▪ Typical Java applications use 20-30% of their memory for String storage
▪ Prior to Java 9, the String class used a UTF-16 representation internally
▪ Most applications use the Latin-1-range of characters
public final class String implements
java.io.Serializable,
Comparable<String>,
CharSequence {
@Stable
private final byte[] value;
private final byte coder;
}
Feature ▪ Use a byte[] instead of a char[]
▪ Use an encoding-flag-field to represent external encoding
▪ Cuts memory footprint in half
3
The jshell features a fully-fledged read-eval-print-loop that
makes API exploration and testing out new things very easy.
jshell> Pattern.compile("(d{2}).(d{2}).(d{4})");
$1 ==> (d{2}).(d{2}).(d{4})
jshell> $1.matcher("14.07.2021");
$2 ==> java.util.regex.Matcher[pattern=...]
jshell> boolean matches = $2.matches()
matches ==> true
Testing a regular expression using jshell
3
It is possible to write out more complex blocks of code than
single-line statements. jshell will indent as appropriate.
jshell> Pattern.compile("(d{2}).(d{2}).(d{4})");
$1 ==> (d{2}).(d{2}).(d{4})
jshell> $1.matcher("14.07.2021");
$2 ==> java.util.regex.Matcher[pattern=...]
jshell> for (int group = 0; group <= $2.groupCount(); group++) {
...> System.out.println(group + ": " + $2.group(group));
...> }
0: 14.07.2021
1: 14
2: 07
3: 2021
Programming with control structures in jshell
3
jshell keeps track of all inputs and allows to save/load
snippets of Java code to a file.
jshell> /list
1 : Pattern pattern = Pattern
.compile("(d{2}).(d{2}).(d{4})");
2 : Matcher matcher = pattern.matcher("14.07.2021");
3 : boolean matches = matcher.matches();
4 : if (matches) System.out.println("matches"); else
System.out.println("does not match");
jshell> /save RegExSnippet.java
Listing all user-given inputs and saving them to a file
4
jshell keeps track of all inputs and allows to save/load
snippets of Java code to a file. (cont.)
jshell> /open RegExSnippet.java
matches
Loading a previously saved code snippet
4
You can also define methods or classes inside a jshell session.
jshell> String helloWorld() {
...> return "Hello world!";
...> }
| created method helloWorld()
jshell> helloWorld();
$1 ==> "Hello world!"
Defining a method and calling it afterwards
4
Java 10
4
Java 10 features the following JEPs.
JEP Title JEP Title
286 Local-Variable Type Inference 317 Experimental Java-Based JIT Compiler
296 Consolidate the JDK Forest into a Single Repo 319 Root Certificates
304 Garbage-Collector Interface 322 Time-Based Release Versioning
307 Parallel Full GC for G1
310 Application Class-Data Sharing
312 Thread-Local Handshakes
313 Remove the Native-Header Generation Tool
314 Additional Unicode Language-Tag Extensions
316 Heap Allocation on Alternative Memory Devices
4
Java 10 refines type inference for variable assignments to
further reduce boilerplate code (JEP 286).
Inference ▪ Derive the type of a variable at initialization
▪ Reassigning is only possible if new type is a supertype of the previous one
▪ Works on
▪ Non-local variables
▪ Lambda parameters
▪ Array initialization
▪ Inside control flow structures
▪ Anonymous classes
▪ Generics
4
Java 10 refines type inference for variable assignments to
further reduce boilerplate code (JEP 286). (cont.)
Simple
var list = new ArrayList<String>(); // infers
// ArrayList<String>
var stream = list.stream(); // infers Stream<String>
Inheritance
var password = new JPasswordFiled("Enter password");
var textField = new JTextField("Random text");
textField = password; // works
password = textField; // won‘t compile
For-Loop
for (var x = 1; x <= 5; x++) {
/* do something */
}
4
Java 10 refines type inference for variable assignments to
further reduce boilerplate code (JEP 286). (cont.)
For-Each-
Loop var list = List.of(1, 2, 3, 4, 5);
for (var item : list) {
/* do something */
}
Ternary
Operator var x = 1 > 0 ? 10 : "I‘m confused!";
var y = 1 < 0 ? 10 : "I‘m confused!";
// type inference looks for the most specialized type
// that satisfies the expression. thus, the examples
// are equivalent to
Serializable x = 1 > 0 ? 10 : "I‘m confused!";
4
There are a couple of limitations that we have to consider when
working with var.
Limitations ▪ Must initialize with a value
▪ Compound delcaration is not allowed
▪ Assigning null is not allowed
var name; // compilation error
var x = 1, y = 2; // compilation error
var x = null; // compilation error
4
There are a couple of limitations that we have to consider when
working with var. (cont.)
Limitations ▪ Lambda expressions require an explicit target type
▪ Method references require an explicit target type
▪ var is not allowed as type of a class member
▪ var is not allowed as type of a method parameter
▪ var is not allowed as a return type
▪ var is not allowed in a catch-clause
var runnable = () -> {}; // compilation error
var abs = Math::abs; // compilation error
4
Java 10 introduces new convenience methods to the Collection
API as well as to Optional<T>.
Optional<T> ▪ T orElseThrow()
Optional
.ofNullable(null)
.orElseThrow(); // throws NoSuchElementException
List<E> ▪ List<E> copyOf(Collection<? extends E> coll)
var list = Arrays.asList(1, 2, 3);
var immutableList = List.copyOf(list);
5
The JVM is now fully container-aware on Linux-based Operating
Systems since Java 10.
Feature ▪ JVM will detect hardware resource limits and use them (default behavior)
▪ New command line flags
▪ Disable container-awareness
-XX:UseContainerSupport
▪ Set the number of cores the JVM can use
-XX:ActiveProcessorCount
▪ Fine-grained control of RAM usage
-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage
5
Java 11
5
Java 11 features the following JEPs.
JEP Title JEP Title
181 Nest-Based Access Control 328 Flight Recorder
309 Dynamic Class-File Constants 329 ChaCha20 and Poly1305 Cryptographic Algorithms
315 Improve Aarch64 Intrinsics 330 Launch Single-File Source-Code Programs
318 Epsilon: A No-Op Garbage Collector 331 Low-Overhead Heap Profiling
320 Remove the Java EE and CORBA Modules 332 Transport Layer Security (TLS) 1.3
321 HTTP Client (Standard) 333 ZGC: A Scalable Low-Latency Garbage Collector
323 Local-Variable Syntax for Lambda Parameters 335 Deprecate the Nashorn JavaScript Engine
324 Key Agreement with Curve25519 and Curve448 336 Deprecate the Pack200 Tools and API
327 Unicode 10
5
JEP 321 standardizes the implementation of the formerly
experimental HTTP Client that comes with Java.
History ▪ Introduced with JDK 9 (experimental), refined with JDK 10
▪ Gone from experimental status to production-grade with JDK 11
Protocols ▪ HTTP/1.1
▪ HTTP/2
▪ HTTP/2 Server Push
▪ WebSockets
Usage Model ▪ Supports a variety of programming models
▪ Synchronous
▪ Asynchronous
▪ Reactive
▪ Provides fluent builders
5
Prior to Java 11, dispatching HTTP requests to an external
website or API was quite cumbersome.
URL url = new URL("http://openjdk.java.net/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String inputLine;
StringBuilder responseBody = new StringBuilder();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream())) {
while ((inputLine = in.readLine()) != null) {
responseBody.append(inputLine);
}
}
conn.disconnect();
System.out.println("Body: " + responseBody);
Using HttpURLConnection and I/O abstractions to fetch a remote site
5
The HTTP Client provides fluent builders that provide
convenient access to all supported programming models.
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://openjdk.java.net/"))
.build();
client.sendAsync(request, asString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
Using the asynchronous interface of the HTTP Client
5
An Authenticator can be used to supply credentials to the
remote server.
HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"username",
"password".toCharArray());
}
}).build()
.send(request, HttpResponse.BodyHandlers.ofString());
Supplying credentials with the new HTTP Client
5
JEP 323 is an extension to the local variable type inference for
lambda parameters
History ▪ Local Variable Type Inference was introduced with Java 10
▪ Allows to infer the dynamic type of an object or primitive type
▪ var keyword
var number = 5; // type is inferred to int
var string = "Hello World!"; // type is inferred to String
var object = BigDecimal.ONE; // type is inferred to BigDecimal
Examples of local variable type inference
5
JEP 323 is an extension to the local variable type inference for
lambda parameters (cont.)
Lambdas ▪ Works on lambda parameters since Java 11 as well
▪ Seems superfluous, but useful when combined with type annotations
Consumer<String> p = (String s) -> System.out.println(s);
Instead of
write
Consumer<String> p = (var s) -> System.out.println(s);
... or simpy stick to
Consumer<String> p = s -> System.out.println(s);
5
JEP 323 is an extension to the local variable type inference for
lambda parameters (cont.)
Lambdas ▪ Works on lambda parameters since Java 11 as well
▪ Seems superfluous, but useful when combined with type annotations
BiConsumer<String, String> p = (@Nonnull String s1,
@Nullable String s2) ->
System.out.println(s1 + (s2 == null ? "" : "" + s2));
Instead of
write
BiConsumer<String, String> p = (@Nonnull var s1,
@Nullable var s2) ->
System.out.println(s1 + (s2 == null ? "" : "" + s2));
6
JEP 323 is an extension to the local variable type inference for
lambda parameters (cont.)
Lambdas ▪ Works on lambda parameters since Java 11 as well
▪ Seems superfluous, but useful when combined with type annotations
BiConsumer<String, String> p = (var s1, String s2) ->
System.out.println(s1 + "" + s2);
It is not possible to mix-and-match
6
JEP 330 allows to launch not-yet-compiled Java source files,
which is useful for single-file scripts or utilities.
History ▪ Up to Java 10 there were three ways to launch a Java program
▪ run a specific .class file
▪ run the main class of a .jar file
▪ run the main class of a Java module
Java 11 ▪ Launch a Java program directly from a Java source file
▪ Works with Shebang interpreter directives (Unix-based systems only)
$> javac HelloWorld.java
$> java –cp . Hello.World
Instead of
write
$> java HelloWorld.java
6
Java 11 features a couple of convenient additions to the Java
class library, most notably when working with strings.
jshell> Character.toString(100)
$1 ==> "d"
jshell> Character.toString(66)
$2 ==> "B"
Character provides a static method that converts Unicode to String
6
Java 11 features a couple of convenient additions to the Java
class library, most notably when working with strings. (cont.)
jshell> "-".repeat(20)
$3 ==> "--------------------"
Extend a string multiple times
6
Java 11 features a couple of convenient additions to the Java
class library, most notably when working with strings. (cont.)
jshell> String msg = "Hello"
msg ==> "Hello"
jshell> msg.isBlank()
$5 ==> false
jshell> String msg = " "
msg ==> " "
jshell> msg.isBlank()
$6 ==> true
String.isBlank can be used to check if a text contains only whitespace
6
Java 11 features a couple of convenient additions to the Java
class library, most notably when working with strings. (cont.)
jshell> String content = "multiline contentnobtained from some
filenwhich we will break into linesnusing
the new api"
content ==> "multiline contentnobtained from some filenwhich we
will break into linesnusing the new api"
jshell> content.lines().forEach(System.out::println)
multiline content
obtained from some file
which we will break into lines
using the new api
Process text line by line
6
Java 11 removes a couple of enterprise packages from Java SE
and deprecates a bunch of other stuff.
Removals ▪ JAX-WS (XML-based SOAP Web Service)
▪ incl. wsgen and wsimport
▪ JAXB (Java XML Bindings)
▪ incl. schemagen and xjc
▪ JAF (Java Beans Activation Framework)
▪ JTA (Java Transaction API)
▪ Common Annotations
▪ @PostConstruct, @Resource, ...
▪ CORBA
▪ JavaFX
▪ Applets
Deprecations ▪ Nashorn JavaScript Engine (JEP 335)
▪ Pack200 Tools and API (JEP 336)
▪ Use jlink instead!
6
Questions?
mguenther.net markus_guenther
mail@mguenther.net

A Journey through the JDKs (Java 9 to Java 11)

  • 1.
    Markus Günther Freelance SoftwareEngineer / Architect mail@mguenther.net | mguenther.net | @markus_guenther Java A Journey Through the JDKs
  • 2.
    2 A brief historyof recent Java versions Version Release End Of Life Java 8 (LTS) 2014.03 2030.12 Java 9 2017.09 2018.03* Java 10 2018.03 2018.09* Java 11 (LTS) 2018.09 2027.09 Java 12 2019.03 2019.09* Java 13 2019.09 2020.03* Java 14 2020.03 2020.09* Java 15 2020.09 2021.03* Java 16 2021.03 2021.09* Java 17 (LTS) 2021.09 TBA
  • 3.
    3 Disclaimer General ▪ Coversnoteworthy features from a developer‘s perspective ▪ Selection is 100% opinionated Early Access ▪ Experimental: Alpha release, activated by flag ▪ Incubator Module: Beta release, separate module underneath jdk.incubator ▪ Preview Feature: Release candidate ▪ Mostly feature complete, semi-stable API, not production-ready Release Highlight Quality of Life Improvement New (Language) Feature
  • 4.
  • 5.
    5 Java 9 featuresthe following JEPs. JEP Title JEP Title 102 Process API Updates 214 Remove GC Combinations Deprecated in JDK 8 110 HTTP 2 Client 215 Tiered Attribution for javac 143 Improve Contended Locking 216 Process Import Statements Correctly 158 Unified JVM Logging 217 Annotations Pipeline 2.0 165 Compiler Control 219 Datagram Transport Layer Security (DTLS) 193 Variable Handles 220 Modular Run-Time Images 197 Segmented Code Cache 221 Simplified Doclet API 199 Smart Java Compilation, Phase Two 222 jshell: The Java Shell (Read-Eval-Print-Loop) 200 The Modular JDK 223 New Version-String Scheme 201 Modular Source Code 224 HTML5 Javadoc 211 Elide Deprecation Warnings on Import Stmts. 225 Javadoc Search 212 Resolve Lint and Doclint Warnings 226 UTF-8 Property Files 213 Milling Project Coin 227 Unicode 7.0
  • 6.
    6 Java 9 featuresthe following JEPs. (cont.) JEP Title JEP Title 228 Add More Diagnostic Commands 245 Validate JVM Command-Line Flag Arguments 229 Create PKC512 Keystores by Default 246 Leverage CPU Instructions for GHASH and RSA 231 Remove Launch-Time JRE Version Selection 247 Compile for Older Platform Versions 232 Improve Secure Application Performance 248 Make G1 the Default Garbage Collector 233 Generate Runtime Compiler Tests Automatically 249 OCSP Stapling for TLS 235 Test Class-File Attributes Gen. by javac 250 Store Interned Strings in CDS Archives 236 Parser API for Nashorn 251 Multi-Resolution Images 237 Linux/AArch64 Port 252 Use CLDR Locale Data by Default 238 Multi-Release JAR Files 253 Prepare JavaFX UI Controls for Modularization 240 Remove the JVM TI hprof Agent Prepare JavaFX CSS APIs for Modularization 241 Remove the jhat Tool 254 Compact Strings 243 Java-Level JVM Compiler Interface 255 Merge Selected Xerces 2.11.0 Updates into JAXP 244 TLS Application-Layer Protocol Negotiation Ext. 256 BeanInfo Annotations
  • 7.
    7 Java 9 featuresthe following JEPs. (cont.) JEP Title JEP Title 257 Update JavaFX/Media to New Ver. of Gstreamer 270 Reserved Stack Areas for Critical Sections 258 HarfBuzz Font-Layout Engine 271 Unified GC Logging 259 Stack-Walking API 272 Platform-Specific Desktop Features 260 Encapsulate Most Internal APIs 273 DRGB-Based SecureRandom Implementations 261 Module System 274 Enhanced Method Handles 262 TIFF Image I/O 275 Modular Java Application Packaging 263 HiDPI Graphics on Windows and Linux 276 Dynamic Linking of Language-Defined Obj. Models 264 Platform Logging API and Service 277 Enhanced Deprecation 265 Marlin Graphics Renderer 278 Additional Tests for Humongous Objects in G1 266 More Concurrency Updates 279 Improve Test-Failure Troubleshooting 267 Unicode 8.0 280 Indify String Concatenation 268 XML Catalogs 281 HotSpot C++ Unit-Test Framework 269 Convenience Factory Methods for Collections 282 jlink: The Java Linker
  • 8.
    8 Java 9 featuresthe following JEPs. (cont.) JEP Title JEP Title 283 Enable GTK 3 on Linux 299 Reorganize Documentation 284 New HotSpot Build System 285 Spin-Wait Hints 287 SHA-3 Hash Algorithms 288 Disable SHA-1 Certificates 289 Deprecate the Applet API 290 Filter Incoming Serialization Data 291 Deprecate the CMS Garbage Collector 292 Implement Sel. ECMAScript 6 Feat. in Nashorn 294 Linux/s390x Port 295 Ahead-of-Time Compilation 297 Unified arm32/arm64 Port 298 Remove Demos and Samples
  • 9.
    9 Java 9 includes91 JEPs. The most noteworthy for developers are based around modularization and API enhancements. JEPs ▪ The Java Platform Module System (JPMS) ▪ jshell: A read-eval-print-loop for Java (REPL) ▪ Private methods in interfaces ▪ Convenient factory methods for collections ▪ Couple of small language and API enhancements ▪ ...
  • 10.
    1 The Java PlatformModule System brings modules as first-class- citizens to Java. History ▪ JSR 376: Java Platform Module System (JPMS) ▪ also known as Project Jigsaw ▪ Closes around a couple of JEPs ▪ the module system itself (JEP 261) ▪ the modular JDK (JEP 200, JEP 201, JEP 220) ▪ encapsulation of internal APIs (JEP 260) ▪ toolchain – jlink (JEP 282) Why? ▪ Strong Encapsulation ▪ Reliable Configuration ▪ Scalable Java SE Platform
  • 11.
    1 The Java PlatformModule System allows us to hide implementation details. module timetracking.invoice package timetracking.invoice.impl package timetracking.invoice.api module timetracking.client package timetracking.client module timetracking.invoice { exports timetracking.invoice.api; } module-info.java module timetracking.client { requires timetracking.invoice; } module-info.java
  • 12.
    1 Think holistically whentransforming the architectural blueprint into the application architecture. Classes Application ? Design considerations and architectural tasks percolate through every layer ▪ Classes are easy to access and use within the code base ▪ ... but classes are no deployment artifacts! ▪ Expose a class as a service? ▪ Copy a class over to another application?
  • 13.
    1 Classes are toofine-grained to be used as the single organizational unit of a large code base. ▪ Group classes into packages ▪ Allows us to reason about design on a higher level of abstraction ▪ How to group things together? Classes Packages Application ? Design considerations and architectural tasks percolate through every layer
  • 14.
    1 Packages can providethe required organizational trait, but are no deployment artifacts. Modules ... ▪ ... can be installed, uninstalled, updated ▪ ... are composable and testable units of deployment ▪ ... can be re-used inside a process Classes Packages Application ? Design considerations and architectural tasks percolate through every layer Modules
  • 15.
    1 A holistic viewon the architecture of an application shows that there are more artifacts at play to provide a proper structure. Classes Packages Modules Application State Deployment and Management Composition and Test Interprocess Reuse Intraprocess Reuse
  • 16.
    1 A holistic viewon the architecture of an application shows that there are more artifacts at play to provide a proper structure. SOA Principles & Patterns Modularity Patterns Package Design Principles & Patterns Quality of Code, Design Patterns, SOLID Packages Modules Application Classes Design considerations and architectural tasks percolate through every layer
  • 17.
    1 The Java PlatformModule System does not satisfy all requirements for a runtime module system. Strong En- capsulation ▪ public classes are visible to all classes in the classpath ▪ It is not possible to hide implementation details ➔ A module system allows to hide implementation details. Dynamic Deployment ▪ Updating a software means re-starting the JVM that runs it ➔ A module system supports hot deployment. ➔ JPMS does not support that. Versioning ▪ Java does not allow to version classes / packages. ▪ What about state migrations? ➔ A module system supports versioning of code artefacts. ➔ JPMS does not support that. Dependency Management ▪ Java does not allow to manage dependencies. ▪ Tools like Maven solve that problem ... ▪ ... but not a runtime! ➔ A module system supports dependency management at runtime. ➔ JPMS does not support that.
  • 18.
    1 The Java PlatformModule System: The good, the bad, the ugly. What’s to like and what not? • A long overdue step towards true software components. • Aggregator modules allow grouping of modules via requires transitive. PRAISE • public no longer means that a class is accessible. • The JPMS does not support versioned modules natively, but only informally. • Split-Packages: Why, just why? • There is only one scope. • No wildcard support when exporting packages. SHAME
  • 19.
    1 The JPMS enablesus to apply a vast variety of modularity patterns. Want to know more? Books ▪ Knoernschild K., Java Application Architecture: Modularity Patterns with Examples Using OSGi, Robert C. Martin Series, Prentice Hall (1st Edition), 03/2012 ▪ Mak S. and Bakker P., Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications, O‘Reilly, 09/2017 Articles ▪ Günther M., Der Weg zu einer modularisierten Java-Anwendung, JavaMagazin, 03/2019, p. 10-18 ▪ Günther M., A Journey to Java 9 Modules (blog series), https://www.mguenther.net/tag/modularity.html, 01/2018
  • 20.
    2 Milling Project Coin(JEP 213) comprises a couple of features wrt. syntactical enhancements. Features ▪ private methods in interfaces ▪ try-with-resources for effectively final AutoCloseables ▪ Anonymous Diamond Operator ▪ @SafeVarargs for Generics and Variable Argument Lists ▪ Underscore is no longer treated as an admissible identifier class X<T> {} X<?> x = new X<>(){}; // X<> is admissible since Java 9 @SafeVarargs private int lengthOf(List<String>... list) { List<String>[] l = list; return l.length; }
  • 21.
    2 Using private methodsin interfaces allows us to break apart default methods into smaller units. public interface UserService { boolean isAllowed(User user, Right right); default List<Right> getRights(User user) { List<Right> userRights = new ArrayList(); user.getRoles().forEach((Role role) -> { userRights.addAll(role.getRights()); }); return userRights; } } A sample interface that uses a default method (Java 8)
  • 22.
    2 Using private methodsin interfaces allows us to break apart default methods into smaller units. (cont.) public interface UserService { boolean isAllowed(User user, Right right); default List<Right> getRights(User user) { List<Right> userRights = new ArrayList(); addAllUserRights(user, userRights); return userRights; } private void addAllUserRights(User user, List<Right> userRights) { user.getRoles().forEach((Role role) -> { userRights.addAll(role.getRights()); }); } } Using a private method to structure the interface implementation (Java 9)
  • 23.
    2 AutoCloseable resources mustnot be initialized with the try- block. They are closed automatically if they are effectively final. try (MyCloseableResource resource = new MyCloseableResource()) { ... } try-with-resources prior to Java 9 MyCloseableResource resource = new MyCloseableResource(); try (resource) { ... } try-with-resources since Java 9
  • 24.
    2 JEP 277 bringsa couple of small changes to Java’s deprecation mechanism. Features ▪ Attribute @Deprecated with properties ▪ since: The version in which the annotated class or method got deprecated ▪ forRemoval: Whether the class or method will be removed in a future release ▪ No longer shows deprecation warning on import @Deprecated(since="9", forRemoval=true) class NoLongerUsed {} class Main { @SuppressWarnings("deprecation") public static void main(String[] args) { NoLongerUsed unused = new NoLongerUsed(); } }
  • 25.
    2 Optional<T> supports acouple of new methods. Methods ▪ void ifPresentOrElse(Consumer<? super T>, Runnable) ▪ Optional<T> or(Supplier<? extends Optional<? extends T>>) Optional<Customer> c = findCustomer(customerId); c.ifPresentOrElse(customer -> onCustomerFound(customer), () -> onMissingCustomer()); Optional<Customer> = findInCache(customerId) .or(() -> findInDatabase(customerId))
  • 26.
    2 Optional<T> supports acouple of new methods. (cont.) Methods ▪ Stream<T> stream() Stream<Optional<String>> optGhostbusters = Stream.of( Optional.of("Peter"), Optional.of("Ray"), Optional.empty(), Optional.of("Egon"), Optional.empty(), Optional.of("Winston")); Stream<String> ghostbusters = optGhostbusters .flatMap(Optional::stream);
  • 27.
    2 Stream<T> supports acouple of new methods. Methods ▪ Stream<T> takeWhile(Predicate<? super T> predicate) ▪ Stream<T> dropWhile(Predicate<? super T> predicate) Stream .iterate(0, i -> i + 1) .takeWhile(n -> n < 10) .forEach(System.out::println); Terminate an infinite stream if a condition no longer holds Stream .of(5, 8, 12, 16, 51) .dropWhile(n -> n < 10) .forEach(System.out::println); Discard elements as long as a condition holds
  • 28.
    2 Stream<T> supports acouple of new methods. (cont.) Methods ▪ Stream<T> ofNullable(T t) collection.stream() .flatMap(s -> { Integer t = map.get(s); return t != null ? Stream.of(t) : Stream.empty(); }) .collect(Collectors.toList()); Handling null values inside a Stream<T> is cumbersome collection.stream() .flatMap(s -> Stream.ofNullable(map.get(s))) .collect(Collectors.toList()); Apply ofNullable(T t) to remove boilerplate code
  • 29.
    2 Stream<T> supports acouple of new methods. (cont.) Methods ▪ Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) Stream .iterate(0, n -> n < 10, i -> i + 1) .forEach(System.out::println);
  • 30.
    3 JEP 269 featuresenhances the Java Collection API by adding factory methods for the construction of immutable collections. List ▪ List<E> of() ▪ List<E> of(E e1) ▪ ... List<String> l = List.of("a", "b", "c"); Set ▪ Set<E> of() ▪ Set<E> of(E e1) ▪ ... Set<String> s = Set.of("a", "b", "c");
  • 31.
    3 JEP 269 featuresenhances the Java Collection API by adding factory methods for the construction of immutable collections. Map ▪ Map<K,V> of() ▪ Map<K,V> of(K k1, V v1) ▪ Map<K,V> of(K k1, V v1, K k2, V v2) ▪ ... Map<String, Integer> m = Map.of( "a", 1, "b", 2, "c", 3);
  • 32.
    3 JEP 266 (MoreConcurrency Updates) most notably introduces a lean API for reactive streams to Java. Publisher Subscriber Subscription subscribe creates subscription notifies subscriber pushes data
  • 33.
    3 Subscriber<T> defines alean interface that let’s us implement the receiving end of a reactive stream. class Sink<T> implements Flow.Subscriber<T> { private Flow.Subscription subscription; @Override public void onSubscribe(Flow.Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(T item) { /* Process item, then request next item(s) */ subscription.request(1); } @Override public void onError(Throwable t) { ... } @Override public void onComplete() { ... } } Simple data sink that is on the receiving end of a reactive stream
  • 34.
    3 A SubmissionPublisher<T> isa Flow.Publisher<T> that implements the asynchronous heavy-lifting for us. Sink<String> sink = new Sink<>(); SubmissionPublisher<String> publisher = new SubmissionPublisher<>(); publisher.subscribe(subscriber); List .of("a", "b", "c", "d", "e", "f") .forEach(publisher::submit); publisher.close(); Subscribe the data sink to the publisher
  • 35.
    3 A Processor<T,R> isa Subscriber<T> and a Publisher<R>, which allows us to build complex reactive processing chains. Publisher Subscriber Subscription Processor Subscription subscribe subscribe
  • 36.
    3 Compact Strings (JEP254) improves the memory consumption of Strings. History ▪ Typical Java applications use 20-30% of their memory for String storage ▪ Prior to Java 9, the String class used a UTF-16 representation internally ▪ Most applications use the Latin-1-range of characters public final class String implements java.io.Serializable, Comparable<String>, CharSequence { @Stable private final byte[] value; private final byte coder; } Feature ▪ Use a byte[] instead of a char[] ▪ Use an encoding-flag-field to represent external encoding ▪ Cuts memory footprint in half
  • 37.
    3 The jshell featuresa fully-fledged read-eval-print-loop that makes API exploration and testing out new things very easy. jshell> Pattern.compile("(d{2}).(d{2}).(d{4})"); $1 ==> (d{2}).(d{2}).(d{4}) jshell> $1.matcher("14.07.2021"); $2 ==> java.util.regex.Matcher[pattern=...] jshell> boolean matches = $2.matches() matches ==> true Testing a regular expression using jshell
  • 38.
    3 It is possibleto write out more complex blocks of code than single-line statements. jshell will indent as appropriate. jshell> Pattern.compile("(d{2}).(d{2}).(d{4})"); $1 ==> (d{2}).(d{2}).(d{4}) jshell> $1.matcher("14.07.2021"); $2 ==> java.util.regex.Matcher[pattern=...] jshell> for (int group = 0; group <= $2.groupCount(); group++) { ...> System.out.println(group + ": " + $2.group(group)); ...> } 0: 14.07.2021 1: 14 2: 07 3: 2021 Programming with control structures in jshell
  • 39.
    3 jshell keeps trackof all inputs and allows to save/load snippets of Java code to a file. jshell> /list 1 : Pattern pattern = Pattern .compile("(d{2}).(d{2}).(d{4})"); 2 : Matcher matcher = pattern.matcher("14.07.2021"); 3 : boolean matches = matcher.matches(); 4 : if (matches) System.out.println("matches"); else System.out.println("does not match"); jshell> /save RegExSnippet.java Listing all user-given inputs and saving them to a file
  • 40.
    4 jshell keeps trackof all inputs and allows to save/load snippets of Java code to a file. (cont.) jshell> /open RegExSnippet.java matches Loading a previously saved code snippet
  • 41.
    4 You can alsodefine methods or classes inside a jshell session. jshell> String helloWorld() { ...> return "Hello world!"; ...> } | created method helloWorld() jshell> helloWorld(); $1 ==> "Hello world!" Defining a method and calling it afterwards
  • 42.
  • 43.
    4 Java 10 featuresthe following JEPs. JEP Title JEP Title 286 Local-Variable Type Inference 317 Experimental Java-Based JIT Compiler 296 Consolidate the JDK Forest into a Single Repo 319 Root Certificates 304 Garbage-Collector Interface 322 Time-Based Release Versioning 307 Parallel Full GC for G1 310 Application Class-Data Sharing 312 Thread-Local Handshakes 313 Remove the Native-Header Generation Tool 314 Additional Unicode Language-Tag Extensions 316 Heap Allocation on Alternative Memory Devices
  • 44.
    4 Java 10 refinestype inference for variable assignments to further reduce boilerplate code (JEP 286). Inference ▪ Derive the type of a variable at initialization ▪ Reassigning is only possible if new type is a supertype of the previous one ▪ Works on ▪ Non-local variables ▪ Lambda parameters ▪ Array initialization ▪ Inside control flow structures ▪ Anonymous classes ▪ Generics
  • 45.
    4 Java 10 refinestype inference for variable assignments to further reduce boilerplate code (JEP 286). (cont.) Simple var list = new ArrayList<String>(); // infers // ArrayList<String> var stream = list.stream(); // infers Stream<String> Inheritance var password = new JPasswordFiled("Enter password"); var textField = new JTextField("Random text"); textField = password; // works password = textField; // won‘t compile For-Loop for (var x = 1; x <= 5; x++) { /* do something */ }
  • 46.
    4 Java 10 refinestype inference for variable assignments to further reduce boilerplate code (JEP 286). (cont.) For-Each- Loop var list = List.of(1, 2, 3, 4, 5); for (var item : list) { /* do something */ } Ternary Operator var x = 1 > 0 ? 10 : "I‘m confused!"; var y = 1 < 0 ? 10 : "I‘m confused!"; // type inference looks for the most specialized type // that satisfies the expression. thus, the examples // are equivalent to Serializable x = 1 > 0 ? 10 : "I‘m confused!";
  • 47.
    4 There are acouple of limitations that we have to consider when working with var. Limitations ▪ Must initialize with a value ▪ Compound delcaration is not allowed ▪ Assigning null is not allowed var name; // compilation error var x = 1, y = 2; // compilation error var x = null; // compilation error
  • 48.
    4 There are acouple of limitations that we have to consider when working with var. (cont.) Limitations ▪ Lambda expressions require an explicit target type ▪ Method references require an explicit target type ▪ var is not allowed as type of a class member ▪ var is not allowed as type of a method parameter ▪ var is not allowed as a return type ▪ var is not allowed in a catch-clause var runnable = () -> {}; // compilation error var abs = Math::abs; // compilation error
  • 49.
    4 Java 10 introducesnew convenience methods to the Collection API as well as to Optional<T>. Optional<T> ▪ T orElseThrow() Optional .ofNullable(null) .orElseThrow(); // throws NoSuchElementException List<E> ▪ List<E> copyOf(Collection<? extends E> coll) var list = Arrays.asList(1, 2, 3); var immutableList = List.copyOf(list);
  • 50.
    5 The JVM isnow fully container-aware on Linux-based Operating Systems since Java 10. Feature ▪ JVM will detect hardware resource limits and use them (default behavior) ▪ New command line flags ▪ Disable container-awareness -XX:UseContainerSupport ▪ Set the number of cores the JVM can use -XX:ActiveProcessorCount ▪ Fine-grained control of RAM usage -XX:InitialRAMPercentage -XX:MaxRAMPercentage -XX:MinRAMPercentage
  • 51.
  • 52.
    5 Java 11 featuresthe following JEPs. JEP Title JEP Title 181 Nest-Based Access Control 328 Flight Recorder 309 Dynamic Class-File Constants 329 ChaCha20 and Poly1305 Cryptographic Algorithms 315 Improve Aarch64 Intrinsics 330 Launch Single-File Source-Code Programs 318 Epsilon: A No-Op Garbage Collector 331 Low-Overhead Heap Profiling 320 Remove the Java EE and CORBA Modules 332 Transport Layer Security (TLS) 1.3 321 HTTP Client (Standard) 333 ZGC: A Scalable Low-Latency Garbage Collector 323 Local-Variable Syntax for Lambda Parameters 335 Deprecate the Nashorn JavaScript Engine 324 Key Agreement with Curve25519 and Curve448 336 Deprecate the Pack200 Tools and API 327 Unicode 10
  • 53.
    5 JEP 321 standardizesthe implementation of the formerly experimental HTTP Client that comes with Java. History ▪ Introduced with JDK 9 (experimental), refined with JDK 10 ▪ Gone from experimental status to production-grade with JDK 11 Protocols ▪ HTTP/1.1 ▪ HTTP/2 ▪ HTTP/2 Server Push ▪ WebSockets Usage Model ▪ Supports a variety of programming models ▪ Synchronous ▪ Asynchronous ▪ Reactive ▪ Provides fluent builders
  • 54.
    5 Prior to Java11, dispatching HTTP requests to an external website or API was quite cumbersome. URL url = new URL("http://openjdk.java.net/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); String inputLine; StringBuilder responseBody = new StringBuilder(); try (BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())) { while ((inputLine = in.readLine()) != null) { responseBody.append(inputLine); } } conn.disconnect(); System.out.println("Body: " + responseBody); Using HttpURLConnection and I/O abstractions to fetch a remote site
  • 55.
    5 The HTTP Clientprovides fluent builders that provide convenient access to all supported programming models. HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://openjdk.java.net/")) .build(); client.sendAsync(request, asString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println) .join(); Using the asynchronous interface of the HTTP Client
  • 56.
    5 An Authenticator canbe used to supply credentials to the remote server. HttpResponse<String> response = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "username", "password".toCharArray()); } }).build() .send(request, HttpResponse.BodyHandlers.ofString()); Supplying credentials with the new HTTP Client
  • 57.
    5 JEP 323 isan extension to the local variable type inference for lambda parameters History ▪ Local Variable Type Inference was introduced with Java 10 ▪ Allows to infer the dynamic type of an object or primitive type ▪ var keyword var number = 5; // type is inferred to int var string = "Hello World!"; // type is inferred to String var object = BigDecimal.ONE; // type is inferred to BigDecimal Examples of local variable type inference
  • 58.
    5 JEP 323 isan extension to the local variable type inference for lambda parameters (cont.) Lambdas ▪ Works on lambda parameters since Java 11 as well ▪ Seems superfluous, but useful when combined with type annotations Consumer<String> p = (String s) -> System.out.println(s); Instead of write Consumer<String> p = (var s) -> System.out.println(s); ... or simpy stick to Consumer<String> p = s -> System.out.println(s);
  • 59.
    5 JEP 323 isan extension to the local variable type inference for lambda parameters (cont.) Lambdas ▪ Works on lambda parameters since Java 11 as well ▪ Seems superfluous, but useful when combined with type annotations BiConsumer<String, String> p = (@Nonnull String s1, @Nullable String s2) -> System.out.println(s1 + (s2 == null ? "" : "" + s2)); Instead of write BiConsumer<String, String> p = (@Nonnull var s1, @Nullable var s2) -> System.out.println(s1 + (s2 == null ? "" : "" + s2));
  • 60.
    6 JEP 323 isan extension to the local variable type inference for lambda parameters (cont.) Lambdas ▪ Works on lambda parameters since Java 11 as well ▪ Seems superfluous, but useful when combined with type annotations BiConsumer<String, String> p = (var s1, String s2) -> System.out.println(s1 + "" + s2); It is not possible to mix-and-match
  • 61.
    6 JEP 330 allowsto launch not-yet-compiled Java source files, which is useful for single-file scripts or utilities. History ▪ Up to Java 10 there were three ways to launch a Java program ▪ run a specific .class file ▪ run the main class of a .jar file ▪ run the main class of a Java module Java 11 ▪ Launch a Java program directly from a Java source file ▪ Works with Shebang interpreter directives (Unix-based systems only) $> javac HelloWorld.java $> java –cp . Hello.World Instead of write $> java HelloWorld.java
  • 62.
    6 Java 11 featuresa couple of convenient additions to the Java class library, most notably when working with strings. jshell> Character.toString(100) $1 ==> "d" jshell> Character.toString(66) $2 ==> "B" Character provides a static method that converts Unicode to String
  • 63.
    6 Java 11 featuresa couple of convenient additions to the Java class library, most notably when working with strings. (cont.) jshell> "-".repeat(20) $3 ==> "--------------------" Extend a string multiple times
  • 64.
    6 Java 11 featuresa couple of convenient additions to the Java class library, most notably when working with strings. (cont.) jshell> String msg = "Hello" msg ==> "Hello" jshell> msg.isBlank() $5 ==> false jshell> String msg = " " msg ==> " " jshell> msg.isBlank() $6 ==> true String.isBlank can be used to check if a text contains only whitespace
  • 65.
    6 Java 11 featuresa couple of convenient additions to the Java class library, most notably when working with strings. (cont.) jshell> String content = "multiline contentnobtained from some filenwhich we will break into linesnusing the new api" content ==> "multiline contentnobtained from some filenwhich we will break into linesnusing the new api" jshell> content.lines().forEach(System.out::println) multiline content obtained from some file which we will break into lines using the new api Process text line by line
  • 66.
    6 Java 11 removesa couple of enterprise packages from Java SE and deprecates a bunch of other stuff. Removals ▪ JAX-WS (XML-based SOAP Web Service) ▪ incl. wsgen and wsimport ▪ JAXB (Java XML Bindings) ▪ incl. schemagen and xjc ▪ JAF (Java Beans Activation Framework) ▪ JTA (Java Transaction API) ▪ Common Annotations ▪ @PostConstruct, @Resource, ... ▪ CORBA ▪ JavaFX ▪ Applets Deprecations ▪ Nashorn JavaScript Engine (JEP 335) ▪ Pack200 Tools and API (JEP 336) ▪ Use jlink instead!
  • 67.