Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new features of JDK 10

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the new features of JDK 10?". Many people will encounter such a dilemma in the operation of actual cases, so 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!

Feature overview

Here are some of the new features introduced in Java 10. A more detailed description of the new features of Java 10 can be found here.

Time-based release control (JEP 322)

Local variable type inference (JEP 286)

Experimental JIT compiler (JEP 317)

Application class data sharing (JEP 310)

Parallel Full GC for G1 (JEP 307)

Clean up garbage Collector Interface (JEP 304)

Other Unicode language tag extensions (JEP 314)

Root certificate (JEP 319)

Thread local handshake (JEP 312)

Heap allocation on standby storage devices (JEP 316)

Delete the native header generation tool-- javah (JEP 313)

Merge JDK forests into a single repository (JEP 296)

API change

one。 Time-based release control (JEP 322)

The past life and present life of the release number

Since the change of ownership of Java, the string naming of JDK distributions has been an intriguing topic.

In terms of the string form of the short version you see when downloading JDK, the number after u before the 7u40 version represents the number of revised versions since JDK was released, but Oracle changed the rules, using odd names in order to highlight major patches (Cirtical Patch Updates) such as security, while maintenance versions such as Bug fixes and API modifications use even numbers. (there is also a version number $MAJOR.$MINOR.$SECURITY format to distinguish between Bug correction and API modification)

To this end, the previous release of JDK 6max 7 has been renamed. (demo below)

Actual Hypothetical Release Type long short-Security 2013 1.7.0_25-b15 7u25 Minor 06 1.7.0_25-b15 7u25 Minor 2013 09 1.7.0_40-b43 7u40 Security 2013 10 1. 7.0_45-b18 7u45 Security 2014/01 1.7.0_51-b13 7u51 Minor 2014/05 1.7.0_60-b19 7u60

As far as the conclusion is concerned, after renaming, starting from 7u9 and 6u37, we can judge whether it is a major patched version from the odd and even numbers; as for the version after 7u40, the major patched version is based on a multiple of 5, with an even number plus one, and the maintenance version will be a multiple of 20. Such (not intuitive) naming is standardized in JEP223. (released with JDK 9)

However, since the release of JDK 8, Mark Reinhold, the Java architect of Oracle, hopes that future Java releases can continue to release new versions based on time and a half-year cycle, so that some useful small features can also be used by developers, so that the specification of JEP 223 is no longer applicable. After the release of JDK 9, they proposed a new version based on the $YEAR.$MONTH format, but received great opposition from the community. Three alternatives were also proposed to collect the views of all parties. (https://goo.gl/7CA8B3)

So, the next feature version of Java is 8.3 to 1803? Or ten? The results of the survey showed that most of the community supported 10jie Stephen Colebourne also issued a request (https://goo.gl/i5J44T)), and said that Java is not like an operating system like Ubuntu, and it is not appropriate to be based on $YEAR.$MONTH.

In the end, Oracle adopted a scheme like $FEATURE.$INTERIM.$UPDATE.$PATCH and specified it in JEP 322.

Interpretation of the New Mode of JEP 322

By adopting a time-based release cycle, Oracle changed the version string scheme and related version information for the Java SE platform and JDK to adapt to current and future time-based release models.

The new mode of the version number is:

$FEATURE.$INTERIM.$UPDATE.$PATCH

$FEATURE: counters will be incremented every 6 months and will be released based on features, such as: JDK 10jjk 11.

INTERIM: counters will be incremented for non-functional versions that contain compatible bug fixes and enhancements but no incompatible changes. Usually, this will be zero, because there will not be any temporary releases within six months. This preserves future revisions to the release model.

UPDATE: counters will be added to address security issues, regression and compatible updated versions of errors in newer features. This feature is updated one month after the feature is released, and every three months thereafter. The April 2018 edition is JDK 10.0.1, the July edition is JDK 10.0.2, and so on.

$PATCH: counters will be incremented for emergency releases to resolve serious problems.

And added a new API to get these counters programmatically:

Version version = Runtime.version (); version.feature (); version.interim (); version.update (); version.patch ()

Now, let's take a look at the Java initiator that returns version information:

$java-version java version "10" 2018-03-20 Java (TM) SE Runtime Environment 18.3 (build 104.46) Java HotSpot (TM) 64-Bit Server VM 18.3 (build 101446, mixed mode)

The version number format is 10 because there are no other counters that are zero. The release date has been added. 18.3 can be understood as Year 2018&3rd Month, and version 10 + 46 is version 46 of version 10. For the hypothetical version 93 of JDK 10.0.1, the version will be 10.0.1 + 93.

Therefore, for Java 9, the current version that can be seen will be in the format of 9.0.4, while the feature version released in March 2018 is 10, and the new version provided in September is expected to be a long-term supported version, so LTS (long-term support) will be specially displayed on the version string.

two。 Local variable type inference (JEP 286)

Overview

One of the most obvious enhancements in JDK 10 is the use of initializers for type inference of local variables.

Before Java 9, we had to explicitly write out the type of local variable and make sure it was compatible with the initializer used to initialize it:

String message = "Good bye, Java 9"

In Java 10, this is how we can declare local variables:

@ Test public void whenVarInitWithString_thenGetStringTypeVar () {var message = "Hello, Java 10"; assertTrue (message instanceof String);}

Instead of providing a specific type of message, we mark message as var, and the compiler will infer the type of message from the type of the initializer on the right. (in the above example, message is of type String)

Note that this feature applies only to local variables with initializers. It cannot be used for member variables, method parameters, return types, and so on-initializing the program is necessary, otherwise the compiler cannot infer its type.

This feature helps us reduce template code, such as:

Map map = new HashMap ()

It can now be rewritten as:

Var idToNameMap = new HashMap ()

This also helps us to focus on variable names rather than variable types.

Another thing to note is that var is not a keyword-- this ensures backward compatibility for programs that use var as the name of a function or variable. Var is a reserved type name, just like int.

Finally, using var does not increase runtime overhead, nor does it make Java a dynamically typed language. The type of the variable is still determined at compile time and cannot be changed later.

Analysis of illegal use of var

1. Without the initialization program, var will not work:

Var n; / / error: cannot use 'var' on variable without initializer

2. If you initialize it to null, it will not work:

Var emptyList = null; / / error: variable initializer is' null'

3. Not applicable to non-local variables:

Public var word = "hello"; / / error: 'var' is not allowed here

4. Lambda expressions require explicit types, so you cannot use var:

Var p = (String s)-> s.length () > 10; / / error: lambda expression needs an explicit target-type

5. The array initialization program does not support:

Var arr = {1,2,3}; / / error: array initializer needs an explicit target-type

Guidelines for using var

In some cases, we can use var legally, but this is not a good idea.

For example, when the readability of the code is reduced:

Var result = obj.prcoess ()

Here, although var can be used legally, it is difficult to understand the type returned by process (), thus making the code less readable.

There is a special article on java.net (OpenJDK website) that introduces the writing guidelines for local variable type inference in Java. This article discusses the posture you should pay attention to when using this feature and some good advice on how to use it.

In addition, another situation where it is best to avoid using var is in streams with longer pipelined lines:

Var x = emp.getProjects.stream () .findFirst () .map (String::length) .orElse (0)

In addition, using var with non-referenced types can result in unexpected errors.

For example, if we use var with an anonymous class instance:

@ Test public void whenVarInitWithAnonymous_thenGetAnonymousType () {var obj = new Object () {}; assertFalse (obj.getClass () .equals (Object.class));}

Now, if we try to assign another Object to obj, there will be a compilation error:

Obj = new Object (); / / error: Object cannot be converted to

This is because the inference type of obj is not Object.

three。 Experimental JIT compiler (JEP 317)

Graal is a dynamic compiler written in Java and integrated with HotSpot JVM. It focuses on high performance and scalability. It is also the basis for the experimental Ahead-of-Time (AOT) compiler introduced in JDK 9.

JDK 10 makes the Graal compiler available as an experimental JIT compiler on Linux / x64 platforms.

To use Graal as the JIT compiler, use the following options on the Java command line:

-XX:+UnlockExperimentalVMOptions-XX:+UseJVMCICompiler

Please note that this is an experimental feature, and we will not necessarily get better performance than the existing JIT compiler.

For more information on children's shoes, please refer to Chris Seaton's speech: https://chrisseaton.com/truffleruby/jokerconf17/

(ps: long text + special bottom warning..)

four。 Application class data sharing (JEP 310)

Class data sharing introduced in JDK 5 allows a set of classes to be preprocessed into shared archive files and then memory mapped at run time to reduce startup time, which also reduces dynamic memory footprint when multiple JVM shares the same archive file.

CDS only allows bootstrap class loaders, limiting this feature to system classes. The application CDS (AppCDS) extends CDS to allow the built-in system class loader. A built-in platform class loader and a custom class loader for loading archive classes. This makes it possible to use this feature with application classes.

We can use the following steps to use this feature:

1. Get the list of classes to be archived

The following command dumps the classes loaded by the HelloWorld application into hello.lst:

$java-Xshare:off-XX:+UseAppCDS-XX:DumpLoadedClassList=hello.lst\-cp hello.jar HelloWorld

2. Create an AppCDS archive

The following command uses hello.lst as input to create hello.js a:

$java-Xshare:dump-XX:+UseAppCDS-XX:SharedClassListFile=hello.lst\-XX:SharedArchiveFile=hello.jsa-cp hello.jar

3. Use AppCDS to archive

The following command starts the HelloWorld application with hello.jsa as input:

$java-Xshare:on-XX:+UseAppCDS-XX:SharedArchiveFile=hello.jsa\-cp hello.jar HelloWorld

AppCDS is a commercial feature in Oracle JDK for JDK 8 and JDK 9. It is now open source and can be used publicly.

five。 Parallel Full GC for G1 (JEP 307)

The G1 garbage collector is the default garbage collector since JDK 9. However, the Full GC of G1 uses a single-threaded mark-sweep-compact algorithm.

It has been changed to the parallel mark-sweep-compact algorithm in Java 10, which effectively reduces the stagnation time during Full GC.

six。 Clean up garbage Collector Interface (JEP 304)

This JEP is the change of the future. It improves the code isolation of different garbage collectors by introducing a common garbage collector interface.

The second change provides better modularity for internal GC code. In the future, it will help to add a new GC without changing the existing code base, as well as to delete or retain the previous GC.

Official motive explanation: (portal)

Currently, each garbage collector implementation consists of source files in its src/hotspot/share/gc/$NAME directory, such as G1 in src/hotspot/share/gc/g1,CMS in src/hotspot/share/gc/cms, and so on. However, there is some scattered information in the HotSpot. For example, most GC requires some obstacles that need to be implemented in the runtime, interpreters C1 and C2. These obstacles are not included in the specific directory of GC, but in the shared interpreter, rather than the implementation, C1 and C2 source code (usually guarded by long if- else-chains). The same problem applies to diagnostic code, such as MemoryMXBeans. This source code layout has several disadvantages:

For GC developers, implementing the new garbage collector requires knowledge of all these places and how to extend them to meet their specific needs.

For HotSpot developers who are not GC developers, where to find specific code snippets for a given GC can cause confusion.

It is difficult to exclude specific garbage collectors at build time. The # define INCLUD E_ALL_GCS has long established a way with only built-in serial collection of JVM, but this mechanism has become too rigid.

A cleaner GC interface will make it easier to implement the new collector, make the code cleaner, and make it easier to exclude one or more collectors at build time. Adding a new garbage collector should implement a documented set of interfaces, rather than figuring out all the areas in HotSpot that need to be changed.

seven。 Other Unicode language tag extensions (JEP 314)

This feature enhances java.util.Locale and related API to implement other Unicode extensions to BCP 47 language tags. Starting with Java SE 9, the supported BCP 47 U language extensions are "ca" and "nu". The JEP will add support for the following additional extensions:

Cu (currency type)

Fw (the first day of the week)

Rg (area coverage)

Tz (time zone)

To support these additional extensions, the following various API have been changed to provide information based on U or additional extensions:

Java.text.DateFormat::get*Instance java.text.DateFormatSymbols::getInstance java.text.DecimalFormatSymbols::getInstance java.text.NumberFormat::get*Instance java.time.format.DateTimeFormatter::localizedBy java.time.format.DateTimeFormatterBuilder::getLocalizedDateTimePattern java.time.format.DecimalStyle::of java.time.temporal.WeekFields::of java.util.Calendar:: {getFirstDayOfWeek,getMinimalDaysInWeek} java.util.Currency::getInstance java.util.Locale::getDisplayName java.util.spi.LocaleNameProvider

eight。 Root certificate (JEP 319)

The cacerts KeyStore (so far empty) is designed to contain a set of root certificates that can be used to establish trust in certificate chains used by various security protocols.

As a result, key security components such as TLS do not work by default in OpenJDK builds.

Open source root certificates in Oracle Java SE Root CA programs with Java 10 Oracle to make OpenJDK builds more attractive to developers and reduce the differences between these builds and Oracle JDK builds.

nine。 Thread local handshake (JEP 312)

This is an internal feature used to improve JVM performance.

A handshake is a callback for each JavaThread when the thread is in a safe point state. The callback is performed by the thread itself or by the VM thread, while keeping the thread in a blocking state.

This feature provides a way to perform callbacks on threads without performing global VM safety points. Makes it possible to stop a single thread instead of stopping all threads or not stopping them at a low cost.

ten。 Heap allocation on standby storage devices (JEP 316)

The memory consumption of applications is increasing, and local cloud applications, in-memory databases, and streaming applications are all increasing. To meet these services, there are a variety of memory architectures available. This feature enhances HotSpot VM's ability to allocate Java object heaps on user-specified spare memory devices, such as NV-DIMM.

The goal of this JEP is to have optional memory devices with the same semantics as DRAM (including the semantics of atomic operations), so it can be used for object heaps instead of DRAM without changing existing application code.

eleven。 Delete the native header generation tool-javah (JEP 313)

This is a general change to remove the javah tool from JDK. The tool functionality, added in javac as part of JDK 8, provides the ability to write native headers that make javah useless at compile time.

twelve。 Merge JDK forests into a single repository (JEP 296)

Over the years, there have been a variety of Mercurial repositories for JDK code bases. Different repositories do offer some advantages, but they also have various operational disadvantages. As part of this change, many of the repositories of JDK Forest have been merged into one repository to simplify and simplify development.

thirteen。 API change

Java 10 adds and removes API. Java 9 introduces enhanced deprecation, in which some API are marked to be deleted in future releases.

So the API is deleted: you can find the deleted API here.

New API: 73 new API in Java 10. You can find the added API here and compare it.

Let's look at the parts that are directly useful to us.

Improvement of immutable sets

There are some changes related to unmodifiable collections in Java 10

CopyOf ()

Java.util.List, java.util.Map, and java.util.Set all have a new static method copyOf (Collection).

It returns an immutable copy of the given Collection:

Jshell > var originList = new ArrayList (); originList = > [] jshell > originList.add ("Welcome to official account:"); $2 = = > true jshell > originList.add ("I don't have three hearts") $3 = > true jshell > var copyList = List.copyOf (originList) copyList = > [Welcome to official account:, I don't have three hearts] jshell > originList.add ("get more wonderful content") $5 = > true jshell > System.out.println (copyList) [Welcome to official account: I don't have three hearts] jshell > copyList.add ("get more wonderful content") | abnormal error java.lang.UnsupportedOperationException | at ImmutableCollections.uoe (ImmutableCollections.java:73) | at ImmutableCollections$AbstractImmutableCollection.add (ImmutableCollections.java:77) | at (# 7:1) jshell >

ToUnmodifiable ()

Java.util.Collectors gets other ways to collect Stream into an immutable List, Map, or Set:

@ Test (expected = UnsupportedOperationException.class) public void whenModifyToUnmodifiableList_thenThrowsException () {List evenList = someIntList.stream () .filter (I-> I% 2 = = 0) .filter (Collectors.toUnmodifiableList ()); evenList.add (4);}

Any attempt to modify such a collection will result in a java.lang.UnsupportedOperationException runtime exception.

Optinal new method orElseThrow ()

Both java.util.Optional,java.util.OptionalDouble,java.util.OptionalInt and java.util.OptionalLong have a new method, orElseThrow (), which takes no arguments and throws NoSuchElementException if no value exists:

@ Test public void whenListContainsInteger_OrElseThrowReturnsInteger () {Integer firstEven = someIntList.stream () .filter (I-> I% 2 = = 0) .findFirst () .orElseThrow (); is (firstEven) .equals (Integer.valueOf (2));}

It is synonymous with the existing get () method and is now its preferred alternative.

That's all for "what are the new features of JDK 10?" 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report