7.1 C
New York

New features to Java 10 and Java 11

Must read

Meghan: Duchess of Sussex tells of miscarriage ‘pain and grief’

"I realized, as I clutched my firstborn kid, that I was getting rid of my second," Meghan stated in a piece for the New...

‘Thanksgiving leftovers won’t style as very good if you are on a ventilator,’ wellness division warns

The public wellbeing messages from authorities in Salt Lake County, Utah, arrive as officers nationwide urge people today to keep household to prevent the...

Messi vs. Ronaldo rivalry resumes as Mbappe, Salah, Neymar, Mane be part of stars in line for top rated award

Cristiano Ronaldo and Lionel Messi resume their rivalry after currently being named on the shortlist for The Finest FIFA Men's Player award, planet football's...

Introduction:

Java 10 and Java 11

The content of the blog is to review the new features being added to in this Java new releases. I’ll not be going over every single feature but will explain about the some of the more important ones that will affect you and your java programs. For example, Java 10 introduces a new release Cadence as well as a new identifier for local variables while Java 11 let us launch a single-file source code programs and standardize the http client API. In java 11, it will execute java source code directly using the Java interpreter.


Java launcher launches the class file , main class of Jar file , main class of module and launch a class declared in an SRC file. Actually, Source code is complied in memory and executed by interpreter.

Now, you will have a question in your mind that where you will learn about all new features that have been released. You can go to the openjdk.java.net/projects/jdk/10 and then /11 for Java 11 new features respectively. When you visit the website, you will see a lot of numbers and acronyms like JSR and JEP.

JSR & JEP acronyms:

  • JSR stands for Java specification request. A JSR describes proposed and final specifications for the Java platform. A JSR may contain several features within it, and by clicking into this you can see the umbrella JSR that contains all of the features organized underneath it.
  • In the Java world, each feature is called JEP or a JDK Enhancement Proposal. Each of the new feature is a JEP . You will probably be familiar with the JDK which is the java development kit for developing the java applications. Now to keep the proposed features organized and identifiable, each JSR and JEP has a number associated with it and that is where these numbers come in. Please see the below screenshot:
  • For Example, in Java 11, JEP 328 refers to Flight Recorder as you can see in the above image. Many of the features introduced in Java 100 & Java 11 involve JVM(Java Virtual machine). JVM is the one which enables a computer to run java programs and other programs compiled to Java byte code by interpreting this byte code.

NEW to Java 10:

Local Variable type Inference:

This feature of java 10 is going to change the way you code in java. Essentially, it is adding some syntactic sugar to Java, simplifying it and improving the developer experience. The new syntax will reduce the wordage and verbosity associated with writing java while retaining its commitment to static-type safety.

Local variable type inference means that you can declare variables without having to specify the associated type. Now, instead of specifying the data type before the variable name, we can just say var.

Before Java 10:

List<String> list = new ArrayList<String> ();

int t = 12;

Here we would go list that contains a string

In java 10:

With Java 10, Here, instead of saying int, instead of specifying what data type that we want the variable to contain , we can use var. The type is inferred from the context. In java 10, if we want to declare an integer variable or a float variable then we do not use to specify the type and simply we can use the “var” keyword and can assign the value

var list = new ArrayList<String> ();

var t =12;

When you say var language equals java( var language = “java”), then the java compiler will already know that the type is string. It’s also important to remember that java is still a statically typed language and once the type is assigned , you can not change it. This means we can not write (language = 3) because already compiler know that language type is string and if you assign it to integer in the next line then it won’t allow.

This feature reduces the amount of boiler plate code needed to declare local variables in java. Now, var is not a general keyword. It is a reserved type name or a context sensitive keyword. This means that the code that uses var as a variable, method or a package name will not be affected. However, code that uses var as a class or interface name will be affected.

Using var as a name for any of these things is rather rare in practice but anyway since it violates the usual naming conventions. Now, how much is this actually going to affect your code? Local variable type interface will be restricted to local variables with initializers , indexes in the enhanced loop , for loop and locals initialized in a traditional for loop. Ex:

Initializers: var me = “Myname”;

Indexes for enhanced for loop: for (var s:myArray)…;

Local variables initialized in traditional for loop: for (var i =0; i<10; i++) …;

Due to Java’s commitment to supporting previous versions of java, we can assume it wont break backwards compatibility. So, now the question arises what does not work with local type variable inference? You must initialize your variable and you can not just declare it. Furthermore, local variable type inference will not be available for method parameters, constructor parameters, method parameters of java development services return types, fields or any other kind of variable declaration. While type inference is not a new concept in java, it is a new concept for local variables. It started in java 5 with generics and then expanded in java 7 as part of Project Coin with the Diamond Operator.

As you know the diamond operator allow us to simplify the code so that we don’t have to specify the data type that the list or array list would contain twice. We only have to do it once (List<String> list = new ArrayList<>();)

Garbage Collection Improvements:

In Java 10, we get a few Garbage collection improvements. In this new version, we get a garbage collector interface, which increases the code isolation of different garbage collectors. It makes it easier to exclude a garbage collector from a JDK build while also making to add a new garbage collector without affecting the code base.

What does this mean? In previous versions of Java, there were bits and pieces of garbage collectors source files scattered all over HotSpot sources. This became an issue when implementing a new Garbage collector since you developers have to know where to look for those source files. One of the main goals of this feature is to introduce better modularity for HotSpot internal garbage collector code, have a cleaner garbage /collector interface and make it easier to implement new collectors.

Before we get into our next new feature, think about cleaning your home. If you have to do, you will do the minimum amount of cleaning in order for it to look presentable. You won’t clean your entire house everyday because that would take lot of resources& time. However, sometimes a deep clean is necessary. Garbage Collection is also kike this.

In java 9, the Garbage-First garbage collector was made the default garbage collector for the JVM which was designed to avoid full Garbage collection. However, when the concurrent collections could not reclaim memory quick enough, it would end up falling back on the full Garbage collectors all one thread creating latencies. In Java 10, the full garbage collector is now parallel. This means that these latencies are lessened because the same number of threads can be used as in current collections, ultimately improving overall performance. When we have to do our deep clean, it is now more efficient.

Memory Allocation to Alternative Devices:

Before we get into this feature, let’s discuss about the HotSpot VM. The HotSpot virtual machine is a core component of the Java SE platform. It implements the java virtual machine specification and it is accessible as a shared library in JRE. It provides java runtime facilities and includes dynamic compilers that adaptively compile java byte codes into optimized machine instructions. The HotSpot VM also manages the java heap using garbage collection and provides data to profiling, monitoring and debugging tools.

HotSpot is also ergonomic JVM meaning based on the platform configuration, it selects a compiler, java heap configuration and garbage collector that produce good to excellent performance for most applications. However, under special circumstances, specific tuning may be required to the best performance and that is where the new features come in.

In Java 10 the HotSpot VM can now allocate the java object heap on an alternative memory device specified by the user. Now why this is good? With the availability of cheap nonvolatile dual inline memory, future systems may have heterogenous memory architectures which, in addition to dynamic random-access memory will have one more type of non-DRAM memory. This feature targets alternative memory devices that have the same semantics as DRAM.

Application Class-data Sharing:

Before going into this feature, let me explain you the class data sharing(CDS). CDS is about the java class files and it allows a set of class files to be pre-processed into a shared archive file.

Now the question arises why would you want to do this?

Each time the JVM loads a class, it must parse the class, store it in an internal structure, performs some checks on it and more. Only after all of this, the class is ready to go. These steps take time , especially when we know certain system classes like String, Integer , URL connection & more are included in Java by default. These classes also require memory so when we have a shared archive that contains pre-processed classes, it can be memory mapped at run time, reducing the start-up time and memory footprint If multiple JVM shares the same archive file.

CDS is part of java since Java 5. Now, what’s the new feature? With CDS, only the bootstrap class loader can load the archived classes. Application CDS, also called as AppCDS extends CDS and allows other class loaders to load achieved classes. Some other class loaders include the built-in system class loader or application class loader and the built-in platform class loader.

Many large -scale enterprise applications often load tens of thousands of classes into the system or application class loader. Applying AppCDS to these applications will result in memory savings of ten to hundreds of megabytes per JVM process.

Server-less cloud services load several thousand application classes at startup and AppCDS can allow these services to start up quickly and improve the overall system response time.In this Java 10 release, CDS can not archive classes from user defined modules but it is planned to support this in future releases.

Thread-local Handshakes:

A JVM safepoint suspends all java threads. Suspending all java threads is necessary to make sure that we only have access to data structures in jvm to safely work with them. Safepoints may be used for garbage collection, code de-optimization and more.

Thread-local handshake feature is essentially trying to reduce the number of global safepoints. The way they do this is by introducing a way to execute a callback on threads without performing a global VM safepoint. This makes it possible and cheap to stop individual threads and not just threads at once laying the groundwork for improved VM performance.

Now, where do the handshakes come in?The handshake is the callback that is executed for each java thread while that thread is in a safepoint-safe state. The call back is executed either by the thread itself or by the VM thread, while keeping the thread in a blocked state. The VM thread will coordinate the handshake operation through a VM operation which will in effect prevent global safepoint from occurring during the handshake operation.

Time-Based Release versioning:

A six-month release cycle is what to expect with a long-term support release every three years. How are these versions represented? The main components are $FEATURE, $INTERIM, $UPDATE and $PATCH. The feature-release counter is incremented for every feature release regardless of the content.

Features might be added in a feature release or they might be removed. If removed, advance notice is given at least one release ahead of time. This used to be called $MAJOR.

The interim-release counter is incremented for non-feature release that contain compatible bug fixes and enhancements but no feature removals and no change to standard APIs. This used to be called $MINOR.

The update-release counter is incremented for compatible update releases that fix security issues, regressions and bugs in new features. This used to be called $SECURITY. The emergency patch-release counter is incremented only when it is necessary to produce an emergency release to fix a critical issue.

Java-Based JIT Compiler:

This feature enables the java based experimental just-in-time compiler, Graal, to be used on the Linux platform. The hotspot Jvm has two runtime compilers called C1 and C2.

C1 is relatively fast and simple compiler that does not do much optimization and is good for application which require a quick startup.

C2 does more optimization and is better for long-running server applications. Both of these are just-in-time compiler.

One more just-in-time compiler for java is called Graal. It is written in java to compile java byte code. Graal was added back in java 9 but with this feature you can enable it with specific JVM arguments(-XX:+UnlockExperimentalVMOptions -XX:+useJVMCICompiler). Enabling the experimental compiler will help the Graal and HotSpot teams investigate the feasibility of a java-based JIT compiler for the JDK.

NEW to Java 11:

New Syntax for Lambda parameters:

If you remember, in Java 10, we got the new identifier “var” for local variables, but we could not use them in lambda expressions. Now, in Java 11, we can use the var for lambda expressions as well. How odes this work? Well in Java 11, we get a new feature that allows us to write as below:

(var n, var m) -> n *m ;

Old syntax was (n, m) -> n*m;
Looking at the above, it does not seem very useful. Why would we want to add the extra verbiage here? Although Java 8 allows us to remove type information so that var is not always necessary. This feature gives us uniformity with local variables More importantly it allows us to add annotations to parameters, like @Nonnull and @Nullable. For ex:

(@Nonnull var n , @Nullable var m) -> n* m


Standardizing the HTTP Client:

The HTTP client was introduced in Java 9, updated in Java 10 and with this feature, it is finally standardized. This means that :

The incubated API has been removed and you’ll now get access to standard API with java.net.http.The incubating API received many rounds of feedback that resulted in significant improvements but the API at a high level remains largely the same.

However, it’s the implementation has been almost rewritten. It’s now asynchronous whereas the previous implementation was blocking and the Rx or the Reactive x flow concept have been pushed down to implementation, eliminating many of the original custom concepts needed to support HTTP2. Furthermore, the flow of data can now be more easily traced from the user level request all the way down to underlying socket connection.

This feature significantly reduces the complexity in the code and maximize the possibility of reuse between HTTP 1.1 and HTTP 2.

Garbage Collectors:

In Java 11, we also get some new garbage collectors. First, we get Epsilon which is a low-overhead garbage collector that handles memory allocation without implementing any mechanism to reclaim memory. This might look strange because it’s a garbage collector that does not want to do any garbage collection. Without reclaiming memory, you will eventually reach the limits of the Java heap and the JVM will exit. Why would you want this? If you wanted to create your own garbage collector, it would provide a good reference implementation to start. It also has some advantages for memory pressure & performance testing.

Another garbage collector we get is the Scalable Low-latency Z garbage collector and it will reduce the length of pauses and handle various heap sizes. It will also lay a foundation of java programming offers for future garbage collector features and optimizations as it leverages pointers and load barriers. The Z garbage collector will only work on Linux for now.

Launch Single-file Source-code Programs:

In Java 11, We will also able to launch single-file source code programs. This allows us to execute our java source code directly using the java interpreter.

In Java 10, the Java launcher operated in 3 modes i.e. launching a class file, launching the main class of a jar file and launching the main class of a module. Java 11 adds fourth mode i.e. launching a class declared in a source file. How does this work?

The source code is compiled in memory and then executed by the interpreter. Suppose for example, we have a “Hello.java” class( This class contains only a main method).

public class HelloJava{

public static void main(String[] args)

System.out.println(String.format(“Hello %s”, args[0]));

Now, to run this java file, we have to execute the command “java Hello.java demoJava “ This will give us the output as “Hello demoJava”. demoJava , I passed from command line and it printed as output.

So, the above we can achieve only in java 11. But what’s the limitation here? Your program must be a single file program where all of the code fits in a single source file. This means that all of your classes must be defined in same file. This feature along with JShell is really great for building simple programs.

Java Flight Recorder:

Instead of using third party tools, Java 11 provides a way to help troubleshoot Java programs with APIs for producing and consuming data as events. While event based JVM tracing has been around for a while, now events can be created, configured and filtered in java.

Flight recorders record events originating from applications, the JVM and OS. Events are stored in a single file and can be inspected using java Mission control.

Some of the JVM arguments to enable Java flight recorder.

java -XX:StartFlightRecording=settings=default// Continuous with dump on demand

If we want to get continuous dump of events on demand, we can write java StartFlightRecording. If we want to get a dump of continues events on exit, then we should just add below arguments:

java -XX:StartFlightRecording=settings=default -XX:FlightRecorderOptions=dumponexit=true,dumponexitpath=C:dump


Here we are including a path where we want to store the final file.

Security Updates:

In Java 11, we also get some security updates. First, the key agreement implementation has been changed. We get TLS version 1.3 with Java 11. This is a major overhaul of the TLS protocol and enhances security and performance. Java 11 also brings in implementation of ChaCha20 and ChaCha20-Poly1305 cryptographic algorithm.

JVM Improvements:

In Java 11, we have dynamic class file constants. This feature extends the Java class file formats to support a new constant pool form including one for compiler implementers and language designers. Next, we have nest-based access control in java 11. This means if you nest multiple classes, they can access each other’s private data. With this, we no longer need to rely on access bridges for this to work.

File API Updates:

Java 11 makes it super easy to read and write strings to and from a file.

File has the “WriteString()” method which takes a path as input that is the file pathand their character sequence i.e. nothing but a String of characters which want to write in a file. This method returns a file path where the file gets created. For Ex:

Path path = Files.writeString(Files.createTempFile(“testFile”, “.txt”), “Java 11 features”);


So here this “writeString()” method returns a path on which the file is created to which it will write the content in a single line.

Now for reading the contents of that file, java 11 provides another method called “readString()” which read the contents of a file and returns the String.

Ex: String str = Files.readString(path);

Other updates in Java 11:

String API updates

IsBlank() method: has been added to String class. If a Java String has any number of blanks inside it then this method will return true. Even if the String contains a single blank(white space) also (String str=””); then the isBlank() method will return true. If the string has at least one character with any number of blanks(white spaces) then the method will return false

Lines()method in Java 11 returns a stream of Strings by splitting the string using the new line character when the string has new line character inside it

IsEmpty() method on Optional Class

Java 11 also provides isEmpty() method on Optional class i.e.helpful when you are working with the reactive programming with Spring. Where when it returns an Optional type, then we can check if it is empty using the isEmpty() method.

Ex:Optional<String> str = Optional.empty();

Deprecations:

Java 11 has removed certain packages likeNashron Java script Engine,Pack200 tools,java.xml.ws, java.activation, java.transaction, java.xml.bind and java.corba. All these packages and classes were part of the JDK earlier. All these were deprecated in earlier version of java bit in JAVA 11 they are completely removed.

So, if you are using any of these, your code will not compile. But if you have a maven project then you can grab these dependencies from the maven repository, and you can still use them. But these are no longer part of JDK in Java 11.

Conclusion:

In this article, you would have got clear conceptual and theoretical knowledge on the new features of Java 10 and Java 11 including the significance of the features in terms of programming aspects.

Some Exciting Offer For You

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

40 + = 41

Latest article

Meghan: Duchess of Sussex tells of miscarriage ‘pain and grief’

"I realized, as I clutched my firstborn kid, that I was getting rid of my second," Meghan stated in a piece for the New...

‘Thanksgiving leftovers won’t style as very good if you are on a ventilator,’ wellness division warns

The public wellbeing messages from authorities in Salt Lake County, Utah, arrive as officers nationwide urge people today to keep household to prevent the...

Messi vs. Ronaldo rivalry resumes as Mbappe, Salah, Neymar, Mane be part of stars in line for top rated award

Cristiano Ronaldo and Lionel Messi resume their rivalry after currently being named on the shortlist for The Finest FIFA Men's Player award, planet football's...

Confront Coverings And Drug Treatment plans Will Enable The Uk Handle Coronavirus Right until A Vaccine Is Located

Face coverings and drug treatment plans will be element of the UK's long-phrase system to deal with the coronavirus ahead...