Personal creation convention: I declare that all articles created are their own original, if there is any reference to any article, will be marked out, if there are omissions, welcome everyone critique. If you find online plagiarism of this article, welcome to report, and actively submit an issue to the Github warehouse, thank you for your support ~
If you don’t like this text version, check out the official Java Insider News no. 20 – Everything you want to know about Java 18
Java 18 is released in GA today (2022-3-22). Today is also the first anniversary of my baby and I getting our license. In honor of this, here is everything you need to know about Java 18
A new feature is released
Simple HTTP server
Relevant JEP:
- JEP 408: Simple Web Server
If you want to take a closer look at the usage, I urge you to check out this video: Java Insider News Issue 16 [Cooked Meat]-Java18 Web Server
JDK 18 comes with a simple HTTP server – jwebServer in the bin directory
You can start a simple HTTP server by using the following command line:
Parameters that can be specified include:
-b addr
or--bind-address addr
: specifies the binding address. Default addr is:127.0.0.1 or: : (1) loopback
-d dir
or--directory dir
By default, dir is the current directory. After mounting, you can obtain the contents in the directory-o level
or--output level
: the specified log level, the default level is info (can be: none | info | verbose)-p port
or--port port
: Specifies the port. The default port is 8000
Access to this simple file server is equivalent to a mount directory:
You can also see the requested accesslog in the console that launches:
127.0.0.1 - - [March 21st, 2020:14:25:48 +0800] "GET/HTTP/1.1" 200 -Copy the code
It only serves HEAD and GET requests and does not support authentication, access control, encryption, etc.
You can customize the configuration of the HTTP server by using the com.sun.net.httpServer class, customize HttpHandler, Filter, etc., for example:
Internet Address resolution SPI
Relevant JEP:
- JEP 418: Internet-Address Resolution SPI
The original Internet address resolution in Java was a built-in parser that used a combination of the local ‘hosts’ file and DNS. After Java 18, SPI was defined for Internet address resolution so that ‘java.net.InetAddress’ can use a parser in addition to the built-in parser.
This is mainly for:
- Prepare for Project Loom: the parse operation for ‘java.net.InetAddress’ currently blocks in operating system calls. This is a problem for Loom’s virtual thread, because it also blocks the virtual thread and prevents the scheduler from switching to another virtual thread. Provide another parser for non-blocking DNS resolution by abstracting this for SPI.
- Compatibility with new network protocols: Seamless integration of new parsing protocols, such as DNS over QUIC/TLS/HTTPS.
- Customizing the results of parsing: Gives frameworks and applications more control over the results of parsing, and allows existing libraries to adapt with custom parsers.
- Better testing: for example, you can implement your own SPI to simulate remote requests actually resolving to some local address, etc.
The SPI is which class, you can refer to Java. Util. ServiceLoader use, through the inside of the API specified SPI interface implementation as follows: java.net.spi.InetAddressResolverProvider
Deprecate For Removal by Finalization
Relevant JEP:
- JEP 421: Deprecate Finalization for Removal
Java Finalization is a feature from the very beginning of Java that was designed to prevent resource leakage: executing a piece of code to reclaim a resource when no one references an instance that holds it. With this in mind, you can imagine that the garbage collector knows when to reclaim an object, so it’s just a good idea to use the garbage collection mechanism to execute this code. So, we design the Object finalize() method, which can be overridden by Java classes that fill in the code to close the resource. This code is called at some point when the object is reclaimed. However, this mechanism raises the following problems:
- If your JVM is growing very slowly in the old age, if you finalize objects into the old age, then objects may not be collected for a long time.
- If you have a sudden increase in objects that need Finalize, you can create those objects faster than GC for collection and execution
finalize()
The speed of the method, which would cause an avalanche - There is no way to determine which thread executes
finalize()
Method, in what order do you execute thesefinalize()
Method, so there can be no thread-safe code in this method, and disorderly references to external objects cause objects to “live” again
Finalization is a historical burden. All garbage collector code has to maintain the mechanism of implementing finalize() methods, which affects the iteration of garbage collector. Finalization also increases the number of pages that GC takes up. The ZGC estimates that 1.5% of the memory footprint is for Finalization purposes only.
So, Object finalize() has been Deprecated since Java 9, and now Deprecated for removal has been Deprecated since Java 18. This method will be removed completely.
How do I verify that removing Finalization has an impact on your project?
If you use JFR, you can check the JFR event jdK.finalizerStatistics that was added after Java 18 to see if there is Finalization in your JVM
If you don’t have JFR on, THEN I recommend you to use JFR, which is very useful, see: JFR complete solution
If you don’t want to go through JFR, you can record it while your application is running:
- Native Memory Tracking is recommended for JVM Memory usage, see system.gc ().
- Number of file descriptors associated with the process
- Direct Buffer and MMAP Buffer usage: this can be viewed by JMX’s MBean, for example:
After recording, add –finalization=disabled to the startup parameter. This parameter invalidates all finalization mechanisms.
The default encoding is UTF-8
Relevant JEP:
- JEP 400: UTF-8 by Default
Many methods in Java take a character encoding set parameter, for example:
new String(new byte[10]);
new String(new byte[10], Charset.defaultCharset());
Copy the code
If not, the system uses the default character set, such as UTF-8 on Linux and MacOS, but not on Windows. Starting with Java 18, the default character set is no longer operating system dependent and is UTF-8.
If you are running Linux, MacOS, or if your startup argument itself has -dfile. encoding=COMPAT then it doesn’t matter to you at all.
If you want to go back to specifying the default character set based on the operating system environment, you can use this startup parameter: -dfile.encoding =COMPAT
Reimplement the Java reflection interface with a MethodHandle
Relevant JEP:
- JEP 416: Reimplement Core Reflection with Method Handles
Prior to JDK 18, there were three INTERNAL JDK mechanisms for reflection operations:
- Vm local method
- The dynamically generated bytecode stub (Method:: Invoke, Constructor::newInstance) and Field access (Field:: Get and set) that relies on the Unsafe class are the main concerns in the broadening class
java.lang.reflect
下 - Method handles (the MethodHandle class) : mainly in
java.lang.invoke
下
Every time you add some new structural feature to Java, such as Record, you need to change all three at once, which is too taxing. So Java 18 implements the second of these apis using classes under Java.lang. Invoke to reduce the amount of work needed to add new language features in the future. This is also in preparation for Project Valhalla’s native value types, which can be allocated on the stack, like STRUCts in C, as well as inline classes in other languages.
Compilable Snippets of Javadoc code
Relevant JEP:
- JEP 413: Code Snippets in Java API Documentation
You can benefit from a clean, up-to-date API documentation with well-documented examples, and it’s even better if the API documentation is compiled and changes as your source code changes. Java 18 gives Javadoc these features.
Let’s write a Maven project to try it out (codebase address: github.com/HashZhang/c…)
First of all, we want to work on common Maven projectssrc/main/java
和 src/test/java
Add a new directorysrc/demo/java
Used to store sample code. Since the sample code is not intended to be packaged into the last released JAR package and needs to be compiled, we mark the sample code directory as the test code directorysrc/test/java
Because we still want to distinguish sample code from unit test code) :We need the Maven plugin to perform javadoc generation, and we need to specify the directory to scan the code snippet (that is, in your source code, the directory to execute the code snippet file, which is the same directory as the source code directorysrc/main/java
Isolated, yessrc/demo/java
) :
First, we create our API class, that is:
As you can see, in the comment we specify the file and the area to read from. Let’s now write sample code:
From the sample code, we can see that the reference area is specified (between @start and @end).
The current project structure is:
performmvn javadoc:javadoc
In thetarget/site
The generated Javadoc can contain code snippets from your project:
You can also highlight some of your comments, or use CSS to edit styles, which I won’t go into here
Preview new features
Switch Mode matching (second preview)
First preview in Java 17 Second preview in Java 18
In Java 17, Sealed Class has been released. With this in mind, we can now do pattern matching on the Switch. A simple example:
In some cases, we might want to enumerate all implementation classes of an interface, for example:
How can we be sure that we have enumerated all of our shapes? Sealed Class allows us to solve this problem by specifying which classes can be inherited by a Sealed Class:
Sealed Class (may be an abstract Class or interface) specifies the names of all the implementation classes. For inherited classes, there are the following restrictions:
- Sealed Class must be in the same module as Sealed Class. If no module is specified, they must be in the same package
- Each inherited Class must inherit Sealed Class directly, not indirectly
- Each inherited class must be one of three:
- Final class, Java Record itself is final
- Sealed’s class, which further specifies which subclasses will be implemented
- A non-sealed class is also an extension to sealed class, but sealed class does not know or care what other subclasses of this class may be.
Here’s an example:
With the Switch pattern matching, the area method above can be rewritten as (we need to add it to the build parameter and startup parameter)--enable-preview
Enable preview) :
If you don’t write default and one type is missing, for example:
A compilation error is reported, which is an exhaustive check for switch pattern matches
In the second preview, we mainly fixed the exhaustive check for closed classes that contain parameter generics, namely, the following closed classes:
For the following code, the exhaustive check does not misreport a compilation error:
This feature also constantly improve, everyone can have a try, and can communicate to the advice here: mail.openjdk.java.net/pipermail/a…
New features in incubation
External functions and memory apis (second incubation)
Relevant JEP:
- The first incubation released in Java 17
- Second incubation released in Java 18
- When will the first preview be released
This is an important feature in the incubation that Project Panama (named after the Panama Canal) brings. Like the Panama Canal that connects the Pacific and Atlantic oceans, Project Panama wants to connect the Java virtual machine to external non-Java libraries. This feature is the most important part of it
The main purpose of this feature is to:
- First, provide an alternative to the ByteBuffer API with similar performance and security features, which fixes some of the shortcomings of the original API (many libraries that need access to off-heap memory, such as Netty operating direct memory as a buffer pool, benefit from this)
- Second, make the library more accessible by replacing JNI with more Java-oriented apis, meaning you can call the system libraries directly from Java code
- And then finally, the unified substitution
sun.misc.Unsafe
The memory access API has been replaced with a package that is easier to use.
Here is an example of using the Foreign Linker API to call MessageBoxW directly from the User32 library on Windows using Java:
Interested can look at this video: Foreign would API: Java native access without C | Modern Java | JDK16 | Head Crashing Informatics 27
There are some interesting projects currently experimenting with external functions and memory apis:
- sqlite-jdbc
- Netty (Refactoring the Buffer Api with Project Panama)
- ElasticSearch
- Lucene
Vector API (Third incubation)
Relevant JEP:
- First incubation in Java 16
- The second incubation in Java 17
- Third incubation in Java 18
This is also an important part of Project Panama. One of the main applications is the use of THE CPU’s SIMD (Single instruction multiple data) processing, which provides a multi-channel data flow through the program, which may have four channels or eight channels, or any number of channels through which a single data element flows. And the CPU organizes operations on all channels in parallel at once, which can greatly increase CPU throughput. With the Vector API, the Java team is working to give Java programmers direct access to it using Java code; In the past, they had to program vector mathematics at the assembly code level or use C/C++ with the intrinsics, which were then made available to Java via JNI.
One of the main optimization points is loops, old loops (scalar loops) that execute on one element at a time, and that’s slow. You can now use the Vector API to convert scalar algorithms into faster data parallel algorithms. An example of using Vector:
Note that using the incubating Java feature requires additional startup arguments to expose the module, in this case –add-modules JDK.incubator. Vector. These arguments need to be added to both the javac compilation and the Java runtime, using IDEA:
Test results:
Fizzbuzz-simd-style is an interesting article (although the performance optimization seems to be not only due to SIMD, but also due to algorithm optimization).
For more detailed usage and design ideas, see this audio: Vector API: SIMD Programming in Java
Wechat search “Dry goods Manman Zhang Hash” follow the public account, a daily brush, easily improve skills, won a variety of offers: