Five of Java 18’s JEPs add new features or major enhancements. See what they do and how they work.
Java 18 was officially released in March, and it included nine implemented JDK Enhancement Proposals (JEPs).
This article covers five of the JEPs in Java 18. The companion article, “The hidden gems in Java 18: The subtle changes,” goes over Java 18’s small improvements and changes that aren’t reflected in those JEPs. It also talks about the four JEPs that are incubators, previews, and deprecations.
Because these articles were researched prior to the March 22 general availability date, I used the Java 18 RC-build 36 jshell tool to demonstrate the code. However, if you would like to test the features, you can follow along with me by downloading the latest release candidate (or the general availability version), firing up a terminal window, checking your version, and running jshell, as follows. Note that you might see a newer version of the build.
[mtaman]:~ java -version
openjdk version "18" 2022-03-22
OpenJDK Runtime Environment (build 18+36-2087)
OpenJDK 64-Bit Server VM (build 18+36-2087, mixed mode, sharing)
[mtaman]:~ jshell --enable-preview
| Welcome to JShell -- Version 18
| For an introduction type: /help intro
jshell>
The nine JEPs in the Java 18 release as are follows:
◉ JEP 400: UTF-8 by default
◉ JEP 408: Simple Web Server
◉ JEP 413: Code snippets in Java API documentation
◉ JEP 416: Reimplement core reflection with method handles
◉ JEP 417: Vector API (third incubator)
◉ JEP 418: Internet address resolution service provider interface
◉ JEP 419: Foreign Function and Memory API (second incubator)
◉ JEP 420: Pattern matching for switch (second preview)
◉ JEP 421: Deprecate finalization for removal
Two of the JEPs are incubator features, one is a preview, and is one is a deprecation, that is, a JEP that prepares developers for the removal of a feature. In this article, I’ll walk through the other five JEPs, and I will not explore the incubators, the preview, and the deprecation.
JEP 400: UTF-8 by default
UTF-8 is a variable-width character encoding for electronic communication and is considered the web’s standard character set (charset). It can encode all the characters of any human language.
The Java standard charset determines how a string is converted to bytes and vice versa. It is used by many methods of the JDK library classes, mainly when you’re reading and writing text files using, for example, the FileReader, FileWriter, InputStreamReader, OutputStreamWriter, Formatter, and Scanner constructors, as well as the URLEncoder encode() and decode() static methods.
Prior to Java 18, the standard Java charset could vary based on the runtime environment’s language settings and operating systems. Such differences could lead to unpredictable behavior when an application was developed and tested in one environment and then run in another environment where the Java default charset changed.
Consider a pre-Java 18 example that writes and reads Arabic text. Run the following code on Linux or macOS to write Arabic content (which means “Welcome all with Java JEP 400”) to the Jep400-example.txt file:
private static void writeToFile() {
try (FileWriter writer = new FileWriter("Jep400-example.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
bufferedWriter.write("مرحبا بكم في جافا جيب ٤٠٠");
}
catch (IOException e) {
System.err.println(e);
}
}
Then read the file back using a Windows system and the following code:
private static void readFromFile() {
try (FileReader reader = new FileReader("Jep400-example.txt");
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line = bufferedReader.readLine();
System.out.println(line);
}
catch (IOException e) {
System.err.println(e);
}
}
The output will be the following:
٠رØبا ب٠٠٠٠جا٠ا ج٠ب Ù¤Ù Ù
This rubbish output happens because, under Linux and macOS, Java saves the file with the default UTF-8 encoding format, but Windows reads the file using the Windows-1252 encoding format.
This problem becomes even worse when you mix text in the same program by writing the file using an older facility, FileWriter, and then reading the contents using newer I/O class methods such as Files writeString(), readString(), newBufferedWriter(), and newBufferedReader(), as in the following:
private static void writeReadFromFile() {
try (FileWriter writer = new FileWriter("Jep400-example.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
bufferedWriter.write("مرحبا بكم في جافا جيب ٤٠٠");
bufferedWriter.flush();
var message = Files.readString(Path.of("Jep400-example.txt"));
System.out.println(message);
}
catch (IOException e) {
System.err.println(e);
}
}
Running the program under Linux and macOS will print the Arabic content without any problem, but doing so on Windows will print the following:
????? ??? ?? ???? ??? ???
These question marks are printed because newer APIs don’t respect the default OS character set and always used UTF-8; so in this case, the file is written with FileWriter using the Windows-1252 charset. When Files.readString(Path.of("Jep400-example.txt")) reads back the file, the method use UTF-8 regardless of the standard charset.
The best solution is to specify the charset when you’re reading or writing files and when calling all methods that convert strings to bytes (and vice versa).
You might think another solution is to set the default charset with the file.encoding system property, as follows:
var fileWriter = new FileWriter("Jep400-example.txt", StandardCharsets.UTF_8);
var fileReader = new FileReader("Jep400-example.txt", StandardCharsets.UTF_8);
Files.readString(Path.of("Jep400-example.txt"), StandardCharsets.UTF_8);
What happens?
[mtaman]:~ java -Dfile.encoding=US-ASCII FileReaderWriterApplication.java
?????????????????????????????????
The result is rubbish because the FileWriter respects the default encoding system property, while Files.readString() ignores it and uses UTF-8. Therefore, the correct encoding should be used to run correctly with -Dfile.encoding=UTF-8.
The goal of JEP 400 is to standardize the Java API default charset to UTF-8, so that APIs that depend on the default charset will behave consistently across all implementations, operating systems, locales, and configurations. Therefore, if you run the previous snippets on Java 18, the code will produce the correct contents.
JEP 408: Simple Web Server
Many development environments let programmers start up a rudimentary HTTP web server to test some functionality for static files. That capability comes to Java 18 through JEP 408.
The simplest way to start the web server is with the jwebserver command. By default, this command listens to localhost on port 8000. The server also provides a file browser to the current directory.
[mtaman]:~ jwebserver
Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
Serving /Users/mohamed_taman/Hidden Gems in Java 18/code and subdirectories on 127.0.0.1 port 8000
URL http://127.0.0.1:8000/
If you visit http://127.0.0.1:8000/, you will see a directory listing in your web browser, and in the terminal you will see the following two lines:
127.0.0.1 - - [06/Mar/2022:23:27:13 +0100] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [06/Mar/2022:23:27:13 +0100] "GET /favicon.ico HTTP/1.1" 404 –
You can change the jwebserver defaults with several parameters, as follows:
[mtaman]:~ jwebserver -b 127.1.2.200 -p 9999 -d /tmp -o verbose
Serving /tmp and subdirectories on 127.0.0.200 port 9999
URL http://127.0.0.200:9999/
Here are a few of the parameters.
◉ -b specifies the IP address on which the server should listen.
◉ -p changes the port.
◉ -d changes the directory the server should serve.
◉ -o configures the log output.
For a complete list of configuration options, run jwebserver -h.
The web server is simple, as its name implies, and has the following limitations:
◉ Only the HTTP GET and HEAD methods are allowed.
◉ The only supported protocol is HTTP/1.1.
◉ HTTPS is not provided.
The API. Fortunately, you can extend and run the server programmatically from the Java API. That’s because jwebserver itself is not a standalone tool; it is a wrapper that calls java -m jdk.httpserver. This command calls the main() method of the sun.net.httpserver.simpleserver.Main class of the jdk.httpserver module, which, in turn, calls SimpleFileServerImpl.start(). This starter evaluates the command-line parameters and creates the server via SimpleFileServer.createFileServer().
You can start a server via Java code as follows:
// Creating the server
HttpServer server = SimpleFileServer.createFileServer(new InetSocketAddress(9999), Path.of("\tmp"), OutputLevel.INFO);
// Starting the server
server.start();
With the Java API, you can extend the web server. For example, you can make specific file system directories accessible via different HTTP paths, and you can implement your handlers to use your choice of paths and HTTP methods, such as PUT and POST. Check the JEP 408 documentation for more API details.
JEP 413: Code snippets in Java API documentation
Prior to Java 18, if you wanted to integrate multiline code snippets into Java documentation (that is, into Javadoc), you had to do it tediously via <pre> ... </pre> and sometimes with {@code ...}. With these tags, you must pay attention to the following two points:
◉ You can’t put line breaks between <pre> and </pre>, which means you may not get the formatting you want.
◉ The code starts directly after the asterisks, so if there are spaces between the asterisks and the code, they also appear in the Javadoc.
Here’s an example that uses <pre> and </pre>.
/**
* How to read a text file with Java 8:
*
* <pre><b>try</b> (var reader = Files.<i>newBufferedReader</i>(path)) {
* String line = reader.readLine();
* System.out.println(line);
* }</pre>
*/
This code will appear in the Javadoc as shown in Figure 1.
0 comments:
Post a Comment