In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the new features of JDK16". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Before we get started, let's take a look at the 17 new features that come with JDK 16. The new feature ▐ will interpret in this article is the migration of the OpenJDK source code repository from Mercurial to Git. Efforts to promote this change will show advantages in terms of version control system metadata size, available tools, and hosting. Migration to GitHub, this change is based on the migration of the OpenJDK source library to Git, and the JDK 16 source code repository will appear on the most popular programmer social networking sites. 386: on x64 and AArch74 architectures, migrate JDK to Alpine Linux and other Linux distributions that use musl as their primary C library. Musl is the Linux implementation of the standard library function described in ISO C and Posix standards. Alpine Linux is widely used in cloud deployment, micro-service and container environment because of its small image. The Docker container image of the Linux version is smaller than 6MB. Let Java run out of the box in such settings, and allow Tomcat, Jetty, Spring, and other popular frameworks to work in these environments. By using jlink to reduce the size of the Java runtime, users can create a smaller image to run a specific application. Pattern matching for the instanceof operator, previewed in both JDK 14 and JDK 15, will be finalized in JDK 16. Pattern matching enables general logic in the program (that is, conditional extraction of components from objects) to be expressed more succinctly and securely. 395: provides Record record classes as transparent carriers of immutable data. ▐ other new features 347: enable C++ 14 language features, allow the use of C++ 14 features in JDK C++ source code, and provide specific guidance on what features are available in HotSpot code. 376: move ZGC (Extensible low-latency garbage Collector) thread stack processing from the safe point to the concurrent phase. The ZGC garbage collector is designed to make GC pauses and scalability issues in HotSpot a thing of the past. Add Unix-Domain Socket Channels, where support for Unix-Domain (AF_UNIX) sockets is added to Socket Channel and Server Socket Channel API in the nio.channels package. 387: the elastic Metaspace function can return the memory occupied by the Class Metadata (Metaspace) of unused HotSpot virtual machines to the operating system more quickly, thus reducing the footprint of Metaspace and simplifying the code of Metaspace to reduce maintenance costs. Porting JDK to Windows/AArch74 platform. 389: the external linker API in the incubation phase supports pure Java access to native code with static types. The goal of this program is to provide interaction with C by replacing JNI (Java native interface) with a more advanced pure Java development mode. Its performance will be superior to that of JNI. 390: warning advice for value-based classes: specify the original wrapper class as a value-based class, discard its constructor for removal, and prompt for a new deprecation warning. An erroneous attempt to synchronize any instance of a value-based class in the Java platform is warned. 392: provides jpackage tools for packaging standalone Java applications. 396: by default, the JDK internal structure is strongly encapsulated, with the exception of critical internal API (such as misc.Unsafe). The goals of this plan include improving the security and maintainability of JDK and encouraging developers to gradually migrate from using internal elements directly to using standard API so that both developers and end users can easily upgrade to future versions of Java. 397: previously previewed in JDK 15, the sealed classes and interfaces in the secondary preview in JDK 16 limit the classes and interfaces that can be extended or implemented. The goals of this plan include allowing the creator of a class or interface to control the code responsible for implementing it, providing a more declarative way to limit the use of superclasses than access modifiers, and supporting the future development of pattern matching by providing a basis for pattern analysis. 338: vector API in the incubation phase (JDK will be equipped with an incubator module), jdk.incubator.vector, to express vector computing compiled into the best hardware instructions on a supported CPU architecture to achieve better performance than equivalent scalar computing. External memory in the incubation phase accesses API, allowing Java programs to securely access external memory outside the Java heap (including local, persistent media, and managed heap memory). As for the identifier numbered JDK Enhancement Process before the new feature above, see Resources at the end of the article. Immediately after browsing the 17 new features, I can't wait to try JDK 16 and some of the features that are helpful to the project. Then first download the candidate version of JDK 16 (http://jdk.java.net/16/) through JDK's official website. For the convenience of switching between multiple JDK versions in the system, you can use jenv (https://github.com/jenv/jenv).
We add the downloaded JDK16 path to jenv and use it after making the following settings. Jenv add ${JDK16_Path} jenv global openjdk64-16 if all goes well, when you look at the JDK version, you will get a return similar to the following. Java-versionopenjdk version "16" 2021-03-16OpenJDK Runtime Environment (build 16-36-2231) OpenJDK 64-Bit Server VM (build 16-36-2231, mixed mode, sharing)
If you are using an earlier version of IDEA as a development tool, you may receive the following error when running a program using JDK 16: Cannot determine path to 'tools.jar' library for 16 (path/to/jdk-16) when running from IDEA, you should update to the latest version.
This is because JDK9 has refactored the Java runtime and removed rt.jar, tools.jar, dt.jar, and various other internal JAR packages. Earlier development tools usually relied on such JAR packages, which could be solved by upgrading IDEA. Go to the official website to get an advance version of IDEA 2021.1 EAP New Features interpretation ▐ migrates to GitHub as early as September 2020, OpenJDK has used the jdk repository on Github as the main read / write repository for JDK 16 source code. With the official release of JDK 16, this will be the first version of JDK developed by OpenJDK on Github. There are three main reasons for migrating OpenJDK source code repositories from Mercurial to Git: version control system metadata, available tools, and available managed size.
In terms of version control metadata size the initial prototype of the converted repository has shown a significant reduction in the size of version control metadata. For example, the .git directory for a jdk repository that uses Git is about 300MB, while the .g directory that uses Mercurial is about 1.2GB. Reducing metadata preserves local disk space and reduces clone time while reducing the amount of data transferred.
In terms of available tools, Git has more tools available than Mercurial. All text editors can achieve Git integration locally or through plug-ins. In addition, almost all IDE come with Git integration, including Eclipse, Visual Studio, and IDEA.
In terms of available hosting, there are many options for hosting Git repositories, whether self-hosted or hosted as a service. Reasons for using external source managed providers include performance, access control for Web API that interacts with developers, and a thriving community.
After OpenJDK migrates to Github, there are still many conveniences for Java developers:
Through a JDK 16 source code warehouse in fork, you can read the source code, take notes and submit it at the same time, which is convenient for continuous learning of JDK source code. Upsteam using Git keeps the JDK source code up-to-date while also keeping itself up-to-date.
If the network speed is fast enough, it is also very convenient to quickly flip through the JDK 16 source code in the browser through Github1s, a tool for online code reading through Github.
If you are working and studying under IDEA, clone is good JDK 16 source code.
Open Project Structure (command+;), set Project SDK to JDK 16, and set Project language level to 16.
After that, you can happily read the JDK 16 source code.
▐ transplants JDK to Alpine Linux in the cloud native era, personal understanding to improve efficiency is the first principle:
Smaller image volumes will be distributed more quickly
Applications / containers should be started quickly
This ensures that the horizontal scaling of the system is fast enough and the rollback is fast enough when problems occur.
In addition, for the sake of cost reduction, a smaller image volume takes up less memory and consumes less resources for distribution. Alpine Linux is an independent, non-commercial general Linux distribution that is in line with the cloud's native efficiency principles.
It focuses on security, simplicity, and resource efficiency, and is built around musl libc and busybox. This makes it smaller than traditional GNU/Linux distributions.
When JDK is migrated to Alpine Linux, it will allow Tomcat, Jetty, Spring, and other popular frameworks to work in it. Users can create a smaller image to start and run specific applications. To prepare Docker in advance, let's first build an Alpine Linux image, then add JDK 16, and finally run a simple Spring Boot program to demonstrate. ▐ to build Alpine Linux image
# get Alpine Linux image, docker pull alpine# running image, docker run alpine echo'Hello Alpineurs'
If you look at the image size through the docker images command, you will find that as of the completion of this article, the image size of alpine is only 5.6MB. Compared with dozens or even hundreds of MB mirrors of debian, ubuntu, centos and other systems, alpine is really small!
REPOSITORY TAG IMAGE ID CREATED SIZEalpine latest 7731472c3f2a 7 weeks ago 5.61MB ▐ add JDK 16
OpenJDK reduces the size of the Java runtime by using jlink (JEP 282: https://openjdk.java.net/jeps/282), and we can get the image from DockerHub: 16-jdk-alpine (https://hub.docker.com/_/openjdk?tab=tags&page=1&name=16-jdk-alpine&ordering=last_updated). Or the following Docker command: docker pull openjdk:16-jdk-alpine
▐ runs Spring Boot
First prepare a Spring Boot FatJar program, you can obtain Hello World from the Spring Boot official website! Sample program (https://spring.io/guides/gs/rest-service/). Create a Dockerfile, use openjdk:16-jdk-alpine, and add a Spring Boot program. FROM openjdk:16-jdk-alpineVOLUME / tmpARG JAR_FILEADD ${JAR_FILE} app.jarENTRYPOINT ["java", "- Djava.security.egd=file:/dev/./urandom", "- jar", "/ app.jar"]
▐ builds and runs
# build an image and set the JAR_FILE parameter to point to the Jar package path of Spring Boot program docker build--build-argJAR_FILE=target/rest-service-0.0.1-SNAPSHOT.jar-t alpine-jdk16-app:latest. # View the image docker images # according to the image, start the container to run #-d parameter run in the background run #-p parameter Spring Boot default port 8080, map to the container port 8080docker run-d-p8080:8080 alpine-jdk16-app:latest # View the container running docker ps # after the verification is successful, you can stop the container docker stop$ {CONTAINER_ID} # access application curl-w'\ n 'http://127.0.0.1:8080/greeting?name=jdk16
At this point, the Spring Boot with JDK 16 runtime through the Alpine Linux system has been started and can be accessed normally.
The Alpine system JDK 16 mirror size is approximately 321MB. Compared with the 467MB of Oracle's official Linux version, it is reduced by 30% +.
The record class provides a preview feature of the Record record class since JDK 14, which will become a permanent feature of JDK 16. The Record record class, as a transparent carrier of immutable data, is in response to complaints that Java is too long and formal. The goals of this plan include designing an object-oriented constructor that represents a collection of simple values, helping developers focus on modeling immutable data rather than extending behavior, and automating data-driven methods such as equals () and property accessors.
This type can be created with a newer version of IDEA:
After declaring the Record record class, there is little need to add additional code, and a set of implicit declarations makes the code very concise:
Properties are implicitly declared
The constructor is implicitly declared
Equals (), hashCode (), toString () are implicitly declared
The accessor of the property is implicitly declared, and the accessor name has the same name as the property
Public record Point (int x, int y) {}
The Record record class supports the Local Classes feature, so when you need to use Record temporarily, it is very convenient to define and use: ListfindTopMerchants (List merchants, int month) {/ / Local record record MerchantSales (Merchant merchant, double sales) {} / use the MerchantSales Record class to temporarily wrap merchant and sales to facilitate processing. Return merchants.stream () .map (merchant-> new MerchantSales (merchant, computeSales (merchant, month)) .sorted ((M1, m2)-> Double.compare (m2.sales (), m1.sales ()) .map (MerchantSales::merchant) .map (toList ()) } the Record record class will replace the tuple functionality previously provided by Tuple, Pair, and other toollibraries outside JDK, and in conjunction with the pattern matching features described below, the code will be very concise. ▐ pattern matching has introduced a preview feature of pattern matching since JDK 14, which will also become a permanent feature of JDK 16. So although JDK 16 is a short-term version, it doesn't prevent us from using pattern matching features in future versions of JDK. At this stage, pattern matching is limited to one pattern (type pattern) and one language construct (instanceof), but this is only part of the complete feature. Even so, we have reaped a significant benefit: redundant conversions have disappeared, redundant code has been eliminated, more important code has been given clearer attention, and bug hiding places have been eliminated. For example: we use if (obj instanceofString) {String s = (String) obj;.} when we need to parse an object in development.
Equivalent code after using pattern matching: if (obj instanceofString s) {/ / by using pattern matching, you can directly use the s local variable.}
Does the code look a lot cleaner?
Using instanceof to get the object type is a form of conditional extraction, and after you get the object type, you always cast the object to that type.
In the past, explicit type conversions had to be performed after instanceof, which is a tedious operation, and the benefit of merging these operations is not only for simplicity, but also eliminates a common source of error: in cutting and pasting instanceof and casting code, it is easy to forget to modify the cast type after changing the type of instanceof, which gives the vulnerability a hiding place. This problem is eliminated by instanceof's pattern matching, and we can also eliminate all this type of bug. Another place where you often need to do this kind of "detect and then cast" is the equals method. Let's look at another example: publicbooleanequals (Object o) {if (! (o instanceof Point)) returnfalse; Point other = (Point) o; return x = = other.x & & y = = other.y;} using the equivalent code after pattern matching: publicbooleanequals (Object o) {return (o instanceof Point other) & & x = = other.x & & y = = other.y;}
This code has the same effect, but is simpler and more straightforward, because we can use only a compound Boolean expression to express an equivalent condition, rather than using a control flow statement. The scope of a pattern-matched binding variable (such as the s of obj instanceof String s in the code example above is a binding variable) is different from that of a "normal" local variable in addition to a special declaration location.
For example, we can write: if (an instanceof Point p) {/ / p is in scope...} else {/ / p not in scope here} / / p not in scope here if (b instanceof Point p) {/ / Sure!.} such a special scope allows us to freely redeclare bound variables in the case of multiple branches of if-else, taking into account the convenience of case in switch in the future. For example: if (x instanceofInteger num) {...} elseif (x instanceofLong num) {.} elseif (x instanceofDouble num) {.} if pattern matching can eliminate 99% of the cast operations in Java code, then it will be very popular. But it's not limited to that. Over time, other types of patterns will emerge that can perform more complex conditional extraction, combine patterns in more complex ways, and provide other constructs that can use patterns: such as switch, or even catch, plus related features such as Record classes that are now permanently supported and sealed classes in the preview. Pattern matching will certainly greatly simplify the code we write in the future. " This is the end of what are the new features of JDK16? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.