In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "what are the new features of JDK9". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the new features of JDK9.
What's New in Java 9
Module system: a module is a package container, and one of the biggest changes in Java 9 is the introduction of the module system (Jigsaw project).
REPL (JShell): interactive programming environment.
HTTP2 client: the HTTP/2 standard is the latest version of the HTTP protocol, and the new HTTPClient API supports WebSocket and HTTP2 streams as well as server push features.
Improved Javadoc:Javadoc now supports searching in API documents. In addition, the output of Javadoc now conforms to the compliant HTML5 standard.
Multi-version compatible JAR package: the multi-version compatible JAR feature allows you to create a version of class that you choose to use when running library programs only in a specific version of the Java environment.
Collection factory methods: in the List,Set and Map interfaces, the new static factory method can create immutable instances of these collections.
Private interface method: use the private private method in the interface. We can use the private access modifier to write private methods in the interface.
Process API: an improved API to control and manage operating system processes. Introducing java.lang.ProcessHandle and its nested interface Info allows developers to escape the dilemma that they often have to use native code in order to obtain the PID of a local process.
Improved Stream API: improved Stream API adds some convenient methods to make stream processing easier and uses collectors to write complex queries.
Improved try-with-resources: if you already have a resource that is final or equivalent to a final variable, you can use that variable in the try-with-resources statement without declaring a new variable in the try-with-resources statement.
The improved deprecated annotation @ Deprecated: the annotation @ Deprecated can mark the Java API status, indicating that the marked API will be removed or broken.
Improved diamond operator (Diamond Operator): anonymous classes can use the diamond operator (Diamond Operator).
Improved Optional class: java.util.Optional adds a lot of new useful methods, and Optional can be converted directly to stream.
Multi-resolution image API: define multi-resolution image API, developers can easily manipulate and display different resolution images.
The improved asynchronous mechanism of the CompletableFuture API: CompletableFuture class can perform operations when the ProcessHandle.onExit method exits.
Lightweight JSON API: a lightweight JSON API is built in
Responsive streaming (Reactive Streams) API: Java 9 introduces a new responsive streaming API to support responsive programming in Java 9.
More new features can be found on the official website: What's New in JDK 9
JDK 9 download address: http://www.oracle.com/technetwork/java/javase/downloads/jdk9-doc-downloads-3850606.html
In the examples of Java 9 articles, we all use the jdk 1.9 environment, and you can view the current version of jdk using the following command:
$java-versionjava version "9-ea" Java (TM) SE Runtime Environment (build 9-ea+163) Java HotSpot (TM) 64-Bit Server VM (build 9-ea+163, mixed mode)
1. Java platform-level module system
The definition function of Java 9 is a completely new module system. The contemporary code base is getting bigger and bigger, and the chances of creating complex, intertwined "spaghetti codes" are increasing exponentially. At this point, you have to face two basic problems: it is difficult to really encapsulate the code, and the system does not have a clear concept of the dependencies between different parts (that is, JAR files). Every public class can be accessed by any other public class under the classpath, which leads to the inadvertent use of API that you do not want to be publicly accessed. In addition, the classpath itself has a problem: how do you know if all the required JAR already exists, or if there will be duplicates? The module system solves both of these problems.
Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed by "requires". In addition, the "exports" statement controls which packages are accessible to other modules. All packages that are not exported are encapsulated in the module by default. The following is an example of a module descriptor that exists in the "module-info.java" file:
Module blog {exports com.pluralsight.blog; requires cms;}
Note that both modules contain encapsulated packages because they are not exported (visualized with orange shields). No one will accidentally use classes from these packages. The Java platform itself is also modularized with its own module system. By encapsulating the inner classes of JDK, the platform is more secure and easier for continuous improvement.
When launching a modular application, JVM verifies that all modules are available, which is based on the requires statement-a big step forward over the fragile classpath. The module allows you to better enforce structured encapsulation of your application and explicitly rely on it. You can learn more about the work of modules in Java 9 in this course.
2. Linking
When you use modules with explicit dependencies and modular JDK, new possibilities arise. Your application module will now declare its dependence on other application modules and on the JDK modules it uses. Why not use this information to create a minimal runtime environment that contains only the modules needed to run the application? This can be achieved through the new jlink tool in Java 9. You can create a minimum runtime image optimized for your application without using a fully loaded JDK installation.
3. JShell: interactive Java REPL
Many languages already have interactive programming environments, and Java now joins the club. You can start jshell from the console and start entering and executing Java code directly. Jshell's immediate feedback makes it a good tool for exploring API and experimenting with language features.
Testing a Java regular expression is a good example of how jshell can make your life easier. Interactive shell can also provide a good teaching environment and improve productivity, and you can learn more here. In the process of teaching people how to write Java, there is no need to explain the nonsense of "public static void main (String [] args)".
4. Improved Javadoc
Sometimes small things can make a big difference. Are you using Google to find the right Javadoc page all the time, just like me? It's not needed anymore. Javadoc now supports searching in API documents. In addition, the output of Javadoc now conforms to the compliant HTML5 standard. In addition, you will notice that each Javadoc page contains information about the source of the JDK module class or interface.
5. Set factory method
Typically, you want to create a collection (for example, List or Set) in your code and populate it directly with some elements. Instantiate the collection, several "add" calls, causing the code to repeat. Java 9, adding several collection factory methods:
Set ints = Set.of (1,2,3); List strings = List.of ("first", "second")
In addition to being shorter and easier to read, these methods also prevent you from choosing a specific collection implementation. In fact, returning a collection implementation that has been put into several elements from a factory method is highly optimized. This is possible because they are immutable: continuing to add elements to these collections after creation results in "UnsupportedOperationException".
6. Improved Stream API
Stream API has long been one of the best improvements to the Java standard library. With this set of API, you can establish a declaration pipeline for transformation on the collection. It will get better in Java 9. Four new methods have been added to the Stream interface: dropWhile, takeWhile, and ofNullable. There is also a new overloaded method for the iterate method that allows you to provide a Predicate (judgment condition) to specify when to end the iteration:
IntStream.iterate (1, I-> I)
< 100 , i ->I + 1) .forEach (System.out::println)
The second parameter is a Lambda, which returns true when the element in the current IntStream reaches 100. So this simple example is to print 1 to 99 to the console.
In addition to the extension of Stream itself, the combination between Optional and Stream has also been improved. You can now convert an Optional object into a (possibly empty) Stream object through Optional's new method stram:
Stream s = Optional.of (1) .stream ()
Converting Optional to Stream is useful when combining complex Stream pipes.
7. Private interface method
Java 8 brings us the default method of the interface. Interfaces can now also contain behaviors, not just method signatures. But what happens if there are several default methods on the interface and the code is almost the same? Typically, you will ReFactor these methods to call a reusable private method. But the default method cannot be private. Creating reuse code as a default method is not a solution because the helper method becomes part of the public API. With Java 9, you can add private helper methods to the interface to solve this problem:
Public interface MyInterface {void normalInterfaceMethod (); default void interfaceMethodWithDefault () {init ();} default void anotherDefaultMethod () {init ();} / / This method is not part of the public API exposed by MyInterface private void init () {System.out.println ("Initializing");}}
If you develop API using the default method, the private interface method may help to build its implementation.
8. HTTP/2
There are new ways to handle HTTP calls in Java 9. This late feature is used to replace the old HttpURLConnection API and provide support for WebSocket and HTTP/2. Note: the new HttpClient API is delivered as a so-called incubator module in Java 9. In other words, this set of API is not guaranteed to be completed at 100%. But you can start using this set of API in Java 9:
HttpClient client = HttpClient.newHttpClient (); HttpRequest req = HttpRequest.newBuilder (URI.create ("http://www.google.com")) .header (" User-Agent "," Java ") .Get () .build (); HttpResponse resp = client.send (req, HttpResponse.BodyHandler.asString ())
HttpResponse resp = client.send (req, HttpResponse.BodyHandler.asString ()); in addition to this simple request / response model, HttpClient provides a new API to handle HTTP/2 features such as streaming and server push.
9. Multiple versions compatible with JAR
The feature we will highlight finally is particularly good news for the maintainers of the library. When a new version of Java appears, it will take years for your library users to switch to the new version. This means that the library has to be backward compatible with the oldest version of Java you want to support (in many cases, Java 6 or 7). This actually means that you won't be able to use the new features provided by Java 9 in the library for a long time in the future. Fortunately, the multi-version compatibility JAR feature allows you to create a version of class that you choose to use when running library programs only in a specific version of the Java environment:
Multirelease.jar ├── META-INF │ └── versions │ └── 9 │ └── multirelease │ └── Helper. Class ├── multirelease ├── Helper. Class └── Main. Class
In the above scenario, multirelease.jar can be used in Java 9, but the class Helper does not use the class of multirelease.Helper at the top level, but the one under "META-INF/versions/9". This is a class version specially prepared for Java 9 and can take advantage of the features and libraries provided by Java 9. At the same time, it is possible to use this JAR in earlier versions of Java, because older versions of Java will only see the top-level Helper class.
10. Multiresolution image API
Java 9 defines multi-resolution image API, so developers can easily manipulate and display images of different resolutions.
The following are the main methods of operation for multi-resolution images:
Image getResolutionVariant (double destImageWidth, double destImageHeight) − acquires an image variant of a specific resolution-represents a logical image of a specific size known to be in DPI, and this image is the best variant.
List getResolutionVariants () − returns a list of image variants at readable resolution.
Example
Import java.io.IOException;import java.net.URL;import java.net.MalformedURLException;import java.util.ArrayList;import java.util.List;import java.awt.Image;import java.awt.image.MultiResolutionImage;import java.awt.image.BaseMultiResolutionImage;import javax.imageio.ImageIO Public class Tester {public static void main (String [] args) throws IOException, MalformedURLException {List imgUrls = List.of ("https://cache.yisu.com/upload/information/20210524/357/10823.png"," https://cache.yisu.com/upload/information/20210524/357/10824.png", "https://cache.yisu.com/upload/information/20210524/357/10825.png"); List images = new ArrayList () For (String url: imgUrls) {images.add (ImageIO.read (new URL (url);} / read all images MultiResolutionImage multiResolutionImage = new BaseMultiResolutionImage (images.toArray (new Image [0])); / / get all resolutions of the image List variants = multiResolutionImage.getResolutionVariants (); System.out.println ("Total number of images:" + variants.size ()); for (Image img: variants) {System.out.println (img) } / / obtain the corresponding image resolution Image variant1 = multiResolutionImage.getResolutionVariant (156,45) according to different sizes; System.out.printf ("\ nImage for destination [% d _ (d)]: [% d _ (d)]", 156,45, variant1.getWidth (null), variant1.getHeight (null)); Image variant2 = multiResolutionImage.getResolutionVariant (311,89) System.out.printf ("\ nImage for destination [% ddjue% d]: [% dje% d]", 311,89, variant2.getWidth (null), variant2.getHeight (null)); Image variant3 = multiResolutionImage.getResolutionVariant (622,178); System.out.printf ("\ nImage for destination [% djue% d]: [% djue% d]", 622,178, variant3.getWidth (null), variant3.getHeight (null)); Image variant4 = multiResolutionImage.getResolutionVariant (300,300) System.out.printf ("\ nImage for destination [% DJI% d]: [% DJ% d]", 300,300, variant4.getWidth (null), variant4.getHeight (null));}}
11.CompletableFuture API
Java 8 introduces the CompletableFuture* class, which may be an explicit completed version of java.util.concurrent.Future (with its value and state set), or it can be used as a java.util.concurrent.CompleteStage. Support future to trigger some dependent functions and actions when it is completed. Java 9 introduces some CompletableFuture improvements:
Java 9 makes improvements to CompletableFuture:
Support for delays and timeouts
Improved support for subclassing
A new factory method
Support for delays and timeouts
Public CompletableFuture completeOnTimeout (T value, long timeout, TimeUnit unit)
Complete the CompletableFutrue with the given value before timeout (units in java.util.concurrent.Timeunits units, such as MILLISECONDS). Return this CompletableFutrue.
Public CompletableFuture orTimeout (long timeout, TimeUnit unit)
If it is not done within the given timeout, the CompletableFutrue is completed with java.util.concurrent.TimeoutException and the CompletableFutrue is returned.
Enhanced support for subclassing
Many improvements have been made so that CompletableFuture can be inherited more easily. For example, you might want to rewrite the new public Executor defaultExecutor () method instead of the default executor.
Another new way to make subclassing easier is:
Public CompletableFuture newIncompleteFuture ()
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.