Java 10 - Quick Guide

Advertisements

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 timeline 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 licensed 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 facility 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 − Consolidate the JDK Forest into a Single Repository

  • JEP 310 − Application 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 Online

We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. 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 online.

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

public class MyFirstJavaProgram {
   public 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 online 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 click 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 Files\java\jdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click 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:\Windows\System32, then edit it the following way

    C:\Windows\System32;c:\Program Files\java\jdk\bin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Edit the 'C:\autoexec.bat' file and add the following line at the end −

    SET PATH=%PATH%;C:\Program Files\java\jdk\bin

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 line 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 like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.

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

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

IDE or Integrated Development Environment, provides all common tools and facilities 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.

public class Tester {
   public 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 initialized at time of declaration otherwise compiler will not be infer and will throw error.

  • Local variable inference is available inside initialization 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;

public class Tester {
   public static void main(String[] args) {
      var names = List.of("Julie", "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.

Julie
Robert
Chris
Joseph

Julie
Robert
Chris
Joseph

Java 10 - New APIs & Options

JDK 10 release has added 70+ new APIs and Options to Java library. 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 inline 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;

public class Tester {
   public static void main(String[] args) {
      var ids = List.of(1, 2, 3, 4, 5); 
      try {
         // get an unmodifiable list
         List<Integer> copyOfIds = List.copyOf(ids);
         copyOfIds.add(6);	
      } catch(UnsupportedOperationException e){
         System.out.println("Collection is not modifiable.");
      }
      try{
         // get an unmodifiable list
         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 library. Following is the relevant details.

  • Unsupported LookAndFeels removed − Applications 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.getLocalizedInputStream and getLocalizedOutputStream Methods removed − Runtime.getLocalizedInputStream and getLocalizedOutputStream Methods are no more available as they were part of an obsolete internationalization 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.

  • policytool removed − The policytool security tool has been removed.

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

    Following deprecated classes are removed

    • com.sun.security.auth.PolicyFile

    • 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 library. 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.Policy API forRemoval − The deprecated javax.security.auth.Policy 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 earlier 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 − Application Class-Data Sharing

When JVM starts it loads the classes in memory as a preliminary 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. Application class-data sharing concept helps in reducing the start up time of an application. Java has an existing CDS (Class-Data Sharing) feature. With Application class-data sharing, Java 10 allows to put application classes in a shared archive. This reduces the application startup and footprint by sharing a common class meta data across multiple java processes.

Process

Application Class data sharing is a 3 step process.

  • Create a list of Classes to archive − Create a list 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 list of classes to be used for Application 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 limited 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::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

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, like 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 like -Xmx, -Xms continue to work.

Java 10 - Consolidated JDK Forest

JEP 296 - Consolidated 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 like −

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

Java 10 onwards, JDK forests are organized into single repository to streamline 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 establish trust in certificates chain of various security protocols of vendors.

OpenJDK builds are not having such certificates which is why critical security components like 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 application threads without making a global VM safepoint. Thus allows JVM to stop an individual thread without stopping all threads.

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

Advertisements