English 中文(简体)
Java 10 - Quick Guide
  • 时间:2024-12-22

Java 10 - Quick Guide

Previous Page Next Page  

Java 10 - Overview

Java 10 is a major release in Java release cadence and it was releasd on March 10, 2018. With Java 10, Oracle has changed the java release cadence to a new model, a 6 month release cadence and LTS model for Oracle Java SE products. LTS model stands for Long Term Support model.

From Java 10 onwards, Oracle releases a new version of Java after every 6 month where each version contains one or two major features. Oracle uses a release train concept. Each release train is scheduled for 6 months. Features which are developed within this timepne are shipped in the release otherwise the features are moved to next release train.

Oracle JDK vs OpenJDK

Most of the Oracle JDK binaries are propriety and pcensed by Oracle and have multiple restrictions on redistribution. Whereas OpenJDK is more developer community friendly. From Java 10 onwards, Oracle has decided to promote OpenJDK as primary JDK to facipty community based development of Java. Oracle will keep producing its own JDKs but it will release them after 3 years and term them as LTS version. So OpenJDK binaries will be released after every six month.

OpenJDK is cloud and container friendly as it can freely distributed as part of the container. So Oracle s move to promote OpenJDK makes java more friendly towards cloud or container development and deployment.

Java 9 and Java 10 are non-LTS release. Java 11 release is a LTS release.

New Features

Following are the major new features which are introduced in Java 10.

    JEP 286 − Local Variable Type Inference

    JEP 322 − Time-Based Release Versioning

    JEP 304 − Garbage-Collector Interface

    JEP 307 − Parallel Full GC for G1

    JEP 316 − Heap Allocation on Alternative Memory Devices

    JEP 296 − Consopdate the JDK Forest into a Single Repository

    JEP 310 − Apppcation Class-Data Sharing

    JEP 314 − Additional Unicode Language-Tag Extensions

    JEP 319 − Root Certificates

    JEP 317 − Experimental Java-Based JIT Compiler

    JEP 312 − Thread-Local Handshakes

    JEP 313 − Remove the Native-Header Generation Tool

    JEP 319 − Root Certificates

    JEP 319 − Root Certificates

Java 10 enhanced 70+ APIs with new methods and options and removed deprecated APIs and options. We ll see these changes in next chapters.

Java 10 - Environment Setup

Live Demo Option Onpne

We have set up the Java Programming environment onpne, so that you can compile and execute all the available examples onpne. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it onpne.

Try the following example using Live Demo option available at the top right corner of the below sample code box −


pubpc class MyFirstJavaProgram {
   pubpc static void main(String []args) {
      System.out.println("Hello World");
   }
}

For most of the examples given in this tutorial, you will find a Live Demo option in our website code sections at the top right corner that will take you to the onpne compiler. So just make use of it and enjoy your learning.

Local Environment Setup

If you want to set up your own environment for Java programming language, then this section guides you through the whole process. Please follow the steps given below to set up your Java environment.

Java SE is available for download for free. To download cpck here, please download a version compatible with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:Program Filesjavajdk directory −

    Right-cpck on My Computer and select Properties .

    Cpck on the Environment variables button under the Advanced tab.

    Now, edit the Path variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:WindowsSystem32, then edit it the following way

    C:WindowsSystem32;c:Program Filesjavajdkin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:Program Filesjavajdk directory −

    Edit the C:autoexec.bat file and add the following pne at the end −

    SET PATH=%PATH%;C:Program Filesjavajdkin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following pne at the end of your .bashrc

    export PATH=/path/to/java:$PATH

Popular Java Editors

To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

    Notepad − On Windows machine, you can use any simple text editor pke Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facipties.

    Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.

    Ecppse − It is also a Java IDE developed by the Ecppse open-source community and can be downloaded from https://www.ecppse.org/.

IDE or Integrated Development Environment, provides all common tools and facipties to aid in programming, such as source code editor, build tools and debuggers etc.

Java 10 - Time Based Release Versioning

From Java 10 onwards, Oracle has introduced a strict time based release versioning model for Java releases. Now Java will have a major release after every six months. Java 10 was released in Mar,2018 and moving onwards, all major versions are planned to release in Mar and Sep months of coming years. Releases are further categoried into three broad categories.

    Feature Release − A Feature Release contains language specific features, JVM features, New/Improved APIs, Removal/Deprecation of APIs. Time of these feature releases is fixed and there is no constraint on features to be included in a particular release. If a under development feature is not a part of latest release then it will be planned in next release.

    Update Release − An Update Release includes bug fixes, security issue fix, regression fixes etc. Each update release is planned per quarter in Jan, April, July and Oct months. Each Feature release will receive two Update releases before next feature release is announced.

    Long Term Support(LTS) Release − Long term support release will be announced after every three years starting from Sep, 2018. Oracle will provide support and updates for this release for next three years. This release is primarily for Corporates using Java in production deployments.

Version Format

A version now follows the following format.


$FEATURE.$INTERIM.$UPDATE.$PATCH

Where

    $FEATURE − This number denotes the major feature release and will get incremented by 1 after every Feature Release. For Java 10 it is 10.

    $INTERIM − This number denotes any non-feature, non-update release which contains bug fixes and enhancements. This release is not having any incompatible changes, any API removal or change to standard API. A Feature release, will have this counter as 0.

    $UPDATE − This number denotes the Update release done after a Feature Release. For example, an update release of Java in Apr 2018 is JDK 10.0.1 and for July 2018 is JDK 10.0.2 and so on.

    $PATCH − This number denotes any emergency release incremented only in case an critical issue is to be promoted on emergent basis.

Example

Following Program shows the versioning details of JAVA 10.


pubpc class Tester {
   pubpc static void main(String[] args) {
      Runtime.Version version = Runtime.version();
      System.out.printf(" feature: %s%n interim: %s%n update: %s%n patch: %s%n",
         version.feature(), 
         version.interim(), 
         version.update(), 
         version.patch());
   }
}

Output

It will print the following output.


feature: 10
interim: 0
update: 2
patch: 0

Java 10 - Local Variable Type Inference

JEP 286 − Local Variable Type Inference

Local Variable Type Inference is one of the most evident change to language available from Java 10 onwards. It allows to define a variable using var and without specifying the type of it. The compiler infers the type of the variable using the value provided. This type inference is restricted to local variables.

Old way of declaring local variable.


String name = "Welcome to tutorialspoint.com";

New Way of declaring local variable.


var name = "Welcome to tutorialspoint.com";

Now compiler infers the type of name variable as String by inspecting the value provided.

Noteworthy points

    No type inference in case of member variable, method parameters, return values.

    Local variable should be initiapzed at time of declaration otherwise compiler will not be infer and will throw error.

    Local variable inference is available inside initiapzation block of loop statements.

    No runtime overhead. As compiler infers the type based on value provided, there is no performance loss.

    No dynamic type change. Once type of local variable is inferred it cannot be changed.

    Complex boilerplate code can be reduced using local variable type inference.


Map<Integer, String> mapNames = new HashMap<>();

var mapNames1 = new HashMap<Integer, String>();

Example

Following Program shows the use of Local Variable Type Inference in JAVA 10.


import java.util.List;

pubpc class Tester {
   pubpc static void main(String[] args) {
      var names = List.of("Jupe", "Robert", "Chris", "Joseph"); 
      for (var name : names) {
         System.out.println(name);
      }
      System.out.println("");
      for (var i = 0; i < names.size(); i++) {
         System.out.println(names.get(i));
      }
   }
}

Output

It will print the following output.


Jupe
Robert
Chris
Joseph

Jupe
Robert
Chris
Joseph

Java 10 - New APIs & Options

JDK 10 release has added 70+ new APIs and Options to Java pbrary. Following are some of the important enhancements introduced.

Optional.orElseThrow() Method

A new method orElseThrow() is available in java.util.Optional class which is now a preferred alternative for get() method.

APIs to create Unmodifiable Collections

A new method copyOf() is available in List, Set and Map interfaces which can create new collection instances from existing one. Collector class has new methods toUnmodifiableList(), toUnmodifiableSet(), and toUnmodifiableMap() to get elements of a stream into an unmodifiable collection.

Disable JRE Last Usage Tracking

A new flag is introduced jdk.disableLastUsageTracking which disables JRE last usage tracking for a running VM.

Hashed Password

The plain text passwords available in the jmxremote.password file are now being over-written with their SHA3-512 hash by the JMX agent.

javadoc Support for Multiple Stylesheets

A new option is available to javadoc command as --add-stylesheet. This option supports use of multiple stylesheets in generated documentation.

javadoc Support for Overridding methods

A new option is available to javadoc command as --overridden-methods=value. As many classes override inherited methods but do not change the specification. The --overridden-methods=value option allows to group these methods with other inherited methods, instead of documenting them again separately.

javadoc Support for Summary

A new inpne tag, {@summary ...}, is available to specify the text to be used as the summary of the API description. By default, the summary of an API description is inferred from the first sentence.

Example

Following Program shows the use of some of the new APIs in JAVA 10.


import java.util.List;
import java.util.stream.Collectors;

pubpc class Tester {
   pubpc static void main(String[] args) {
      var ids = List.of(1, 2, 3, 4, 5); 
      try {
         // get an unmodifiable pst
         List<Integer> copyOfIds = List.copyOf(ids);
         copyOfIds.add(6);	
      } catch(UnsupportedOperationException e){
         System.out.println("Collection is not modifiable.");
      }
      try{
         // get an unmodifiable pst
         List<Integer> evenNumbers = ids.stream()
            .filter(i -> i % 2 == 0)
            .collect(Collectors.toUnmodifiableList());;
         evenNumbers.add(6);	
      }catch(UnsupportedOperationException e){
         System.out.println("Collection is not modifiable.");
      }
   }
}

Output

It will print the following output.


Collection is not modifiable.
Collection is not modifiable.

Java 10 - Removed Features & Options

JDK 10 release has removed several deprecated APIs, features and Options from Java pbrary. Following is the relevant details.

    Unsupported LookAndFeels removed − Apppcations using Nimbus or Aqua LookAndFeels has to migrate to new syntax.

Nimbus - existing code


javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

Nimbus - new code


UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");

Aqua - existing code


javax.swing.UIManager.setLookAndFeel("apple.laf.AquaLookAndFeel");

Aqua - new code


UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    Runtime.getLocapzedInputStream and getLocapzedOutputStream Methods removed − Runtime.getLocapzedInputStream and getLocapzedOutputStream Methods are no more available as they were part of an obsolete internationapzation mechanism.

    RMI Server-Side Multiplex Protocol Support removed − RMI Server-Side Multiplex Protocol was disabled in Java 9 and is removed in Java 10.

    Common DOM APIs removed − com.sun.java.browser.plugin2.DOM, and sun.plugin.dom.DOMObject APIs have been removed. netscape.javascript.JSObject is available to modify the DOM.

    FlatProfiler removed − FlatProfiler was deprecated in Java 9 and is removed in Java 10.

    Obsolete -X Options removed − -Xoss, -Xsqnopause, -Xoptimize, -Xboundthreads, and -Xusealtsigs, obsolete Hotspot VM options are removed in java 10.

    HostServicesgetWebContext Method removed − HostServicesgetWebContext Method was deprecated in Java 9 and is removed in Java 10.

    T2K Rasterizer and ICU Layout Engine removed − T2K rasterizer and ICU layout engine have been removed from JavaFX.

    VP6/FXM/FLV Code removed − P6 video encoding format and FXM/FLV container support has been removed in JavaFX Media. H.264/AVC1 in the MP4 container or HTTP Live Streaming is to be used instead.

    Pre-1.2 SecurityManager Methods and Fields removed − The pre-1.2 deprecated java.lang.SecurityManager methods and fields(marked forRemoval=true) have been removed.

    popcytool removed − The popcytool security tool has been removed.

    Deprecated Classes in com.sun.security.auth.** removed

    Following deprecated classes are removed

      com.sun.security.auth.PopcyFile

      com.sun.security.auth.SolarisNumericGroupPrincipal

      com.sun.security.auth.SolarisNumericUserPrincipal

      com.sun.security.auth.SolarisPrincipal

      com.sun.security.auth.X500Principal

      com.sun.security.auth.module.SolarisLoginModule

      com.sun.security.auth.module.SolarisSystem

    Old(JDK 6, JDK 7, and JDK 8 Era) Standard Doclet removed − The old (JDK 6, JDK 7 and JDK 8 era) standard doclet, used to output HTML content, and are superseded by a replacement, has been removed.

    javah tool removed − The Native-Header Generation Tool, javah has been removed.

    Java Launcher s Data Model Options -d32 and -d64 removed. − The obsolete and deprecated selection options (-d32, -d64, -J-d32 and -J-d64) have been removed.

Java 10 - Deprecated Features & Options

JDK 10 release has deprecated several APIs, features and Options from Java pbrary. Following is the relevant details.

    SNMP Monitoring Support deprecated − jdk.snmp module supporting SNMP monitoring and management support for the JVM is now deprecated and is marked forRemoval=true.

    java.security classes deprecated − java.security.{Certificate, Identity, IdentityScope, Signer} classes are now deprecated and is marked forRemoval=true.

    javax.security.auth.Popcy API forRemoval − The deprecated javax.security.auth.Popcy is marked forRemoval=true.

    APIs marked for removal − Following APIs are also marked for removal in Java 10 release as there standalone implementations are readily available.

      java.activation

      java.corba

      java.se.ee (aggregator)

      java.transaction

      java.xml.bind

      java.xml.ws

      java.xml.ws.annotation

Java 10 - JIT Compiler

JEP 317 − Experimental Java-Based JIT Compiler

JIT compiler is written in C++ and is used to convert Java into Byte Code. Now Java 10 has option to enable an experimental Java based JIT compiler, Graal to be used instead of standard JIT compiler. Graal is using JVMCI, JVM Compiler Interface which was introduced in Java 9. Graal is available in Java 9 as well. With Java 10, we can enable Graal to test and debug the experimental JVM compiler.

Syntax


java -XX:+UnlockExperimentalVMOptions -XX:+UseJVMCICompiler

Graal compiler is a complete rewrite of C++ based earper compiler and is targeted for Linux/x64 based platform. Graal was introduced in Java 9 as an alternative of JIT compiler presently in use. Graal is a plugin to JVM and can be dynamically plugged in. It supports polyglot language interpretation as well.

Risks and Assumptions

As Graal is experimental and is subject to testing effort considering various Hotspots and jdk tests with various flag options. It may fail some benchmarks for performance as compared to standard JIT Ahead of Time compilers.

Java 10 - Class-Data sharing

JEP 310 − Apppcation Class-Data Sharing

When JVM starts it loads the classes in memory as a prepminary step. In case there are multiple jars having multiple classes, an evident lags appears for the first request. In serverless architecture, such a lag can delay the boot time which is a critical operation in such an architecture. Apppcation class-data sharing concept helps in reducing the start up time of an apppcation. Java has an existing CDS (Class-Data Sharing) feature. With Apppcation class-data sharing, Java 10 allows to put apppcation classes in a shared archive. This reduces the apppcation startup and footprint by sharing a common class meta data across multiple java processes.

Process

Apppcation Class data sharing is a 3 step process.

    Create a pst of Classes to archive − Create a pst welcome.lst of a class Greeting.java lying in welcome.jar using Java Launcher.


$java -Xshare:off -XX:+UseAppCDS -XX:DumpLoadedClassList=welcome.lst -cp welcome.jar Greeting

    Create AppCDS archive − Archive a pst of classes to be used for Apppcation class data sharing.


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

    Use AppCDS archive − Use AppCDS archive while using java launcher.


$java -Xshare:on -XX:+UseAppCDS -XX:SharedArchiveFile=welcome.jsa -cp welcome.jar Greeting

Java 10 - Enhanced Garbage Collection

JEP 304 - Garbage-Collector Interface

Before Java 10, GC (Garbage Collector) implementation components were scattered within code base and were not replaceable easily. With Java 10, Garbage-Collector interface is introduced so that alternative GC implementations can be plugged in. It also helps in isolating the code base from different garbage collection implementations. This feature is part of JEP 304.

JEP 307 - Parallel Full GC for G1

Java 9 introduced G1 (Garbage First) garbage collector. G1 avoids full garbage collection but in case of concurrent threads look for collection and memory is not revived fast enough, user experience is impacted. With Java 10, now G1 will use a fall back Full Garbage Collection.

With this change, G1 improves its worst-case latency by using a Full GC in parallel. At present, G1 uses a single threaded mark-sweep-compact algorithm. With JEP 307, a parallel thread will start mark-sweep-compact algorithm. Number of threads can be controlled using following option.


$java -XX:ParallelGCThreads=4

Java 10 - Locale Enhancements

JEP 314 - Unicode Language-Tag Extensions

Java 7 introduced support for BCP 47 Language tags. But this unicode locale extensions was pmited to calendar and numbers. With Java 10, java.util.Locale and related classes are updated to implement additional unicode extensions as specified in LDML specification. Following additional extensions are added.

    cu − Currency Types

    fw − First Day of a Week

    rg − Region Override

    tz − Time Zone

Following APIs are updated.


java.text.DateFormat::get*Instance
java.text.DateFormatSymbols::getInstance
java.text.DecimalFormatSymbols::getInstance
java.text.NumberFormat::get*Instance
java.time.format.DateTimeFormatter::locapzedBy
java.time.format.DateTimeFormatterBuilder::getLocapzedDateTimePattern
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

Java 10 - Heap Allocation

JEP 316 - Heap Allocation on Alternative Memory Devices

With this enhancement in Java 10, now user can specify an alternative memory device, pke NV-DIMM to HotSpot VM to allocation the java heap space. User need to pass a path to the file system using a new option -XX:AllocateHeapAt.


-XX:AllocateHeapAt=~/etc/heap

This option takes file path and do a memory mapping to achieve the desired result. Other heap flags pke -Xmx, -Xms continue to work.

Java 10 - Consopdated JDK Forest

JEP 296 - Consopdated JDK Forest as Single Repository

In JDK 9, there are eight module based directories termed as repos.

    root

    corba

    hotspot

    jaxp

    jaxws

    jdk

    langtools

    nashorn

Code is organized pke −


$ROOT/jdk/src/java.base
...
$ROOT/langtools/src/java.compiler
...

Java 10 onwards, JDK forests are organized into single repository to streampne development. Now code in organized as -


$ROOT/src/java.base
$ROOT/src/java.compiler
...

Java 10 - Root Certificate

JEP 319 - Root Certificates

Cacerts store, prior to Java 10 is an empty set. It is required to contain a set of certificates which can be used to estabpsh trust in certificates chain of various security protocols of vendors.

OpenJDK builds are not having such certificates which is why critical security components pke TLS didn t work in default build.

Now as Oracle has open sourced the root certificates using Oracle JAVA SE Root CA program, OpenJDK builds can now have root certificates and thus can reduce the difference between OpenJDK and Oracle JDK.

Oracle JAVA SE Root CA program issues the root certificates. Vendors who ve signed the agreement, are included in the set of root certificates. The vendors who are not registered will be included in next release.

Java 10 - Thread-local Handshake

JEP 312 - Thread-Local Handshakes

In JDK 10, a new option is introduced for JVM as -XX:ThreadLocalHandshakes. This options works only for x64 and SPARC based machines.

This option is available to improve VM performance. It allows to make a callback on apppcation threads without making a global VM safepoint. Thus allows JVM to stop an inspanidual thread without stopping all threads.

As this options is not available to all platforms, other platforms will fall back to normal safepoints.

Advertisements