Book Image

Java 11 Cookbook - Second Edition

By : Nick Samoylov, Mohamed Sanaulla
Book Image

Java 11 Cookbook - Second Edition

By: Nick Samoylov, Mohamed Sanaulla

Overview of this book

For more than three decades, Java has been on the forefront of developing robust software that has helped versatile businesses meet their requirements. Being one of the most widely used programming languages in history, it’s imperative for Java developers to discover effective ways of using it in order to take full advantage of the power of the latest Java features. Java 11 Cookbook offers a range of software development solutions with simple and straightforward Java 11 code examples to help you build a modern software system. Starting with the installation of Java, each recipe addresses various problem by explaining the solution and offering insights into how it works. You’ll explore the new features added to Java 11 that will make your application modular, secure, and fast. The book contains recipes on functional programming, GUI programming, concurrent programming, and database programming in Java. You’ll also be taken through the new features introduced in JDK 18.3 and 18.9. By the end of this book, you’ll be equipped with the skills required to write robust, scalable, and optimal Java code effectively.
Table of Contents (18 chapters)

What's new in Java 11?

The release of Java 9 was a milestone in the Java ecosystem. The modular framework developed under Project Jigsaw became part of Java SE release. Another major feature was the JShell tool, which is a REPL tool for Java. Many other new features introduced with Java 9 are listed in the release notes: http://www.oracle.com/technetwork/java/javase/9all-relnotes-3704433.html.

In this recipe, we will enumerate and discuss some of the new features introduced with JDK 18.3 and 18.9 (Java 10 and 11).

Getting ready

The Java 10 release (JDK 18.3) started a six-month release cycle—every March and every September—and a new release numbering system. It also introduced many new features, the most significant of which (for application developers) are the following:

  • Local variable type inference that allows the declaration of a variable using the reserved var type (see Chapter 15, The New Way of Coding with Java 10 and Java 11)
  • Parallel full garbage collection for the G1 garbage collector, which improves worst-case latencies
  • A new method, Optional.orElseThrow(), that is now the preferred alternative to the existing get() method
  • New APIs for creating unmodifiable collections: The List.copyOf(), Set.copyOf(), and Map.copyOf() methods of the java.util package and new methods of the java.util.stream.Collectors class: toUnmodifiableList(), toUnmodifiableSet(), and toUnmodifiableMap() (see Chapter 5, Streams and Pipelines)
  • A default set of root Certification Authorities, making OpenJDK builds more appealing to developers
  • A new Javadoc command-line option, --add-stylesheet, provides support for the use of multiple stylesheets in the generated documentation
  • Extending the existing class-data sharing feature to allow application classes to be placed in the shared archive that improves startup time and reduces the footprint (see the Using application class-data sharing recipe)

  • An experimental just-in-time compiler, Graal, can be used on the Linux/x64 platform
  • A clean garbage-collector (GC) interface that makes it simpler to add a new GC to HotSpot without perturbing the current code base and makes it easier to exclude a GC from a JDK build
  • Enabling HotSpot to allocate the object heap on an alternative memory device, such as an NVDIMM memory module, specified by the user
  • Thread-local handshakes, for executing a callback on threads without performing a global VM safepoint
  • Docker awareness: JVM will know whether it is running in a Docker container on a Linux system and can extract container-specific configuration information instead of querying the operating system
  • Three new JVM options, to give Docker container users greater control over the system memory

See the full list of Java 10's new features in the release notes: https://www.oracle.com/technetwork/java/javase/10-relnote-issues-4108729.html.

We will discuss the new features of JDK 18.9 in more detail in the next section.

How to do it...

We have picked a few features that we feel are the most important and useful for an application developer.

JEP 318 – Epsilon

Epsilon is a so-called no-op garbage collector that basically does nothing. Its use cases include testing for performance, memory pressure, and the virtual machine interface. It also could be used for short-lived jobs or the jobs that do not consume much memory and do not require garbage collection.

We discussed this feature in more details in the recipe Understand Epsilon, a low-overhead garbage collector recipe in Chapter 11, Memory Management and Debugging.

JEP 321 – HTTP Client (Standard)

JDK 18.9 standardizes the incubated HTTP API client introduced in JDK 9 and updated in JDK 10. Based on CompleteableFuture, it supports nonblocking requests and responses. The new implementation is asynchronous and provides a better traceable data flow.

Chapter 10, Networking, explains this feature in more detail in several recipes.

JEP 323 – Local-Variable Syntax for Lambda Parameters

A local-variable syntax for lambda parameters has the same syntax as a local-variable-declaration using the reserved var type introduced in Java 11. See the Using local variable syntax for lambda parameters recipe in Chapter 15, The New Way of Coding with Java 10 and Java 11, for more details.

JEP 333 – ZGC

The Z Garbage Collector (ZGC) is an experimental low-latency garbage collector. Its pause times should not exceed 10 ms and there should be no more than 15% application throughput reduction compared to using the G1 collector. ZGC also lays a foundation for future features and optimizations. Linux/x64 will be the first platform to get ZGC support.

New API

There are several additions to the standard Java API:

  • Character.toString(int codePoint): Returns a String object representing the character specified by the provided Unicode code point:
var s = Character.toString(50);
System.out.println(s); //prints: 2
  • CharSequence.compare(CharSequence s1, CharSequence s2): Compares two CharSequence instances lexicographically. Returns the difference between the position of the second parameter and the position of the first parameter in the ordered list:
var i = CharSequence.compare("a", "b");
System.out.println(i); //prints: -1

i = CharSequence.compare("b", "a");
System.out.println(i); //prints: 1

i = CharSequence.compare("this", "that");
System.out.println(i); //prints: 8

i = CharSequence.compare("that", "this");
System.out.println(i); //prints: -8
  • The repeat(int count) method of the String class: Returns a String value composed of count times repeated in the String source value:
String s1 = "a";
String s2 = s1.repeat(3); //prints: aaa
System.out.println(s2);

String s3 = "bar".repeat(3);
System.out.println(s3); //prints: barbarbar
  • The isBlank() method of the String class: Returns true if the String value is empty or contains only white spaces, otherwise false. In our example, we have contrasted it with the isEmpty() method, which returns true if, and only if, length() is zero:
String s1 = "a";
System.out.println(s1.isBlank()); //false
System.out.println(s1.isEmpty()); //false

String s2 = "";
System.out.println(s2.isBlank()); //true
System.out.println(s2.isEmpty()); //true

String s3 = " ";
System.out.println(s3.isBlank()); //true
System.out.println(s3.isEmpty()); //false

  • The lines() method of the String class: Returns a Stream object that emits lines extracted from the source String value, separated by line terminators \n, \r, or \r\n:
String s = "l1 \nl2 \rl3 \r\nl4 ";
s.lines().forEach(System.out::print); //prints: l1 l2 l3 l4
  • Three methods of the String class that remove leading space, trailing space, or both from the source String value:
String s = " a b ";
System.out.println("'" + s.strip() + "'"); // 'a b'
System.out.println("'" + s.stripLeading() + "'"); // 'a b '
System.out.println("'" + s.stripTrailing() + "'");// ' a b'
  • Two Path.of() methods that construct a java.nio.file.Path object:
Path filePath = Path.of("a", "b", "c.txt");
System.out.println(filePath); //prints: a/b/c.txt

try {
filePath = Path.of(new URI("file:/a/b/c.txt"));
System.out.println(filePath); //prints: /a/b/c.txt
} catch (URISyntaxException e) {
e.printStackTrace();
}
  • The asMatchPredicate() method of the java.util.regex.Pattern class, which creates an object of the java.util.function.Predicate functional interface, which then allows us to test a String value for matching the compiled pattern. In the following example, we test whether a String value starts with the a character and ends with the b character:
Pattern pattern = Pattern.compile("^a.*z$");
Predicate<String> predicate = pattern.asMatchPredicate();
System.out.println(predicate.test("abbbbz")); // true
System.out.println(predicate.test("babbbz")); // false
System.out.println(predicate.test("abbbbx")); // false

There's more...

There are quite a few other changes introduced in JDK 18.9:

  • The Java EE and CORBA modules are removed
  • JavaFX is separated and removed from the Java standard libraries
  • The Pack200 and Unpack200 tools and the Pack200 API in util.jar are deprecated
  • The Nashorn JavaScript engine, along with the JJS tool, are deprecated with the intent to remove them in the future
  • The Java class file format is extended to support a new constant pool form, CONSTANT_Dynamic
  • Aarch64 intrinsics are improved, with the implementation of new intrinsics for the java.lang.Math sin, cos, and log functions, on Aarch64 processorsJEP 309—Dynamic Class-File Constants
  • Flight Recorder provides a low-overhead data-collection framework for troubleshooting both Java applications and the HotSpot JVM
  • The Java launcher can now run a program supplied as a single file of Java source code, so these programs can run directly from the source
  • A low-overhead heap profiling, providing a way to sample Java heap allocations, is accessible via JVM Tool Interface
  • Transport Layer Security (TLS) 1.3 increases security and improves performance
  • Support of Unicode version 10.0 in the java.lang.Character, java.lang.String, java.awt.font.NumericShaper, java.text.Bidi,java.text.BreakIterator, and java.text.Normalizer classes

Read the Java 11 (JDK 18.9) release notes for more details and other changes.