Java 10 – New Features (APIs & Options) ”; Previous Next 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. Java 10 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 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 – 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. Useful Links Deprecation Features Options Removal Features Options Print Page Previous Next Advertisements ”;
Category: Java
Java – Inner Class Diamond Operator ”; Previous Next Java Diamond Operator The diamond operator was introduced in Java 7 to make code more readable for Generics. A generic is a type of argument. Using generic we can pass any kind of object to be processed by the class methods. For example, if we are creating a list of strings before Java 7, then we”ve to use the following syntax to instantiate a list of strings with an ArrayList object. List<String> listOfStrings = new ArrayList<String>(); From Java 7 onwards, we can use diamond operator to simplify the above syntax as following − List<String> listOfStrings = new ArrayList<>(); But it could not be used with Anonymous inner classes. For example, we cannot omit the object type from diamond operator in below syntax prior to Java 9. Handler<Integer> intHandler = new Handler<Integer>(1) { @Override public void handle() { System.out.println(content); } }; Diamond Operator in Anonymous Class In Java 9, the diamond operator can be used with an anonymous class as well to simplify code and improve readability. Handler<Integer> intHandler = new Handler<>(1) { @Override public void handle() { System.out.println(content); } }; Diamond Operator in Java 7, Java 8 In below example, we”ve created anonymous classes for an abstract class Handler accepting a generic argument and pass the object type while creating the anonymous class as we have to pass the type argument otherwise program won”t compile. Example public class Tester { public static void main(String[] args) { // create an Anonymous class to handle 1 // Here we need to pass Type arguments in diamond operator // before Java 9 otherwise compiler will complain error Handler<Integer> intHandler = new Handler<Integer>(1) { @Override public void handle() { System.out.println(content); } }; intHandler.handle(); // create an Anonymous class to handle 2 Handler<? extends Number> intHandler1 = new Handler<Number>(2) { @Override public void handle() { System.out.println(content); } }; intHandler1.handle(); Handler<?> handler = new Handler<Object>(“test”) { @Override public void handle() { System.out.println(content); } }; handler.handle(); } } abstract class Handler<T> { public T content; public Handler(T content) { this.content = content; } abstract void handle(); } Output Let us compile and run the above program, this will produce the following result − 1 2 Test Diamond Operator Java 9 Onwards With Java 9, we can use <> operator with anonymous class as well as shown below. Example In below example, we”ve created anonymous classes for an abstract class Handler accepting a generic argument but without the object type while creating the anonymous class as we need not to pass the type argument. Compiler infers the type itself. public class Tester { public static void main(String[] args) { // create an Anonymous class to handle 1 // Here we do not need to pass Type arguments in diamond operator // as Java 9 compiler can infer the type automatically Handler<Integer> intHandler = new Handler<>(1) { @Override public void handle() { System.out.println(content); } }; intHandler.handle(); Handler<? extends Number> intHandler1 = new Handler<>(2) { @Override public void handle() { System.out.println(content); } }; intHandler1.handle(); Handler<?> handler = new Handler<>(“test”) { @Override public void handle() { System.out.println(content); } }; handler.handle(); } } abstract class Handler<T> { public T content; public Handler(T content) { this.content = content; } abstract void handle(); } Output Let us compile and run the above program, this will produce the following result − 1 2 Test Print Page Previous Next Advertisements ”;
Java – Z Garbage Collectors (ZDC) ”; Previous Next What is ZGC? ZDC stands for Z Garbage Collector. Z Garbage Collector, ZDC was introduced with Java 11 as a low latency garbage collection mechnism. ZGC was introduced in Java 11 as an experimental feature as developer community felt it to be too large to be released early. ZGC makes sure that Garbage Collection pause time is not dependent on heap size. It will never exceed 10 ms no matter heap size is 2MB or 2GB. But ZGC had a limitation on returning unused heap memory to operating system like other HotSpot VM GCs such as G1 and Shenandoah. Java 15 made the ZGC, Z Garbage Collector a standard feature. It was an experimental feature till Java 15. It is low latency, highly scalable garbage collector. ZGC is highly performant and works efficiently even in case of massive data applications e.g. machine learning applications. It ensures that there is no long pause while processing the data due to garbage collection. It supports Linux, Windows and MacOS. Features of Z Garbage Collector With Java 16, ZGC Thread-Stack processing is moved from Safepoints to Concurrent Phase and improved its efficiency to great extent. Following are the enhancements made to garbage collection since then, for example − ZGC returns uncommited memory to operating system by default until the maximum heap size is reached. ZGC gives performance improvement with a reduced memory footprint. ZGC now supports heap size of 16 TB as compared to 4TB size limit. Thread-stack processing moved from ZGC safepoints. Stack processing is made lazy, cooperative, concurrent, and incremental. All other per-thread root processing are removed from ZGC safepoints. HotSpot subsystems can lazily process stacks. Concurrent class unloading Uncommiting of unused memory Support for Class Data Sharing NUMA Awareness Multithreaded Heap Pre-touch Max Heap Size limit from 4 TB to 16 TB. Using Older way of Garbage Collection In order to move back to Java 11 way of Garbage Collection, we can use following options: using -XX:-ZUncommit option set -Xms and -Xmx heap size as same. Print Page Previous Next Advertisements ”;
Java – CompletableFuture API Improvements ”; Previous Next CompletableFuture class was introduced in Java 8 to represent the Future which can be completed by setting its value and status explicity. It can be used as java.util.concurrent.CompletionStage. It supports dependent functions and actions which got triggered upon the future”s completion. In java 9 CompletableFuture API has been enhanced further. Following are the relevant changes done to the API. Support for delays and timeouts. Improved support for subclassing. New factory methods added. Support for delays and timeouts public CompletableFuture<T> completeOnTimeout(T value, long timeout, TimeUnit unit) This method completes this CompletableFuture with the given value if not otherwise completed before the given timeout. public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) This method exceptionally completes this CompletableFuture with a TimeoutException if not otherwise completed before the given timeout. Improved support for subclassing public Executor defaultExecutor() It returns the default Executor used for async methods that do not specify an Executor. This method may be overridden in subclasses to return an Executor to provide one independent thread as minimum. public <U> CompletableFuture<U> newIncompleteFuture() Returns a new incomplete CompletableFuture of the type to be returned by a CompletionStage method. Subclasses of CompletableFuture class should override this method to return an instance of the same class as this CompletableFuture. The default implementation returns an instance of class CompletableFuture. New factory Methods public static <U> CompletableFuture<U> completedFuture(U value) This factory method returns a new CompletableFuture which is already completed with the given value. public static <U> CompletionStage<U> completedStage(U value) This factory method returns a new CompletionStage which is already completed with the given value and supports only those methods present in interface CompletionStage. public static <U> CompletionStage<U> failedStage(Throwable ex) This factory method returns a new CompletionStage which is already completed exceptionally with the given exception and supports only those methods present in interface CompletionStage. Print Page Previous Next Advertisements ”;
Java – Multi-catch Block
Java Multiple Catch Blocks ”; Previous Next Multiple Catch Blocks in Java Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown from a particular code section. A try block can have multiple catch blocks to handle multiple exceptions. Syntax: Multiple Catch Blocks try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Points to Remember while using Multiple Catch Blocks Only one type of exception can be handled at a time. In protected, only one type of exception will be raised, so it will be handled in relevant catch block only. Order of catch block is very important. Order should be from specific exception to generic one. In case of parent exception block comes before the child exception block, compiler will complain and will throw compile time error. Example of Java Multiple Catch Blocks Here is code segment showing how to use multiple try/catch statements. In this example, we”re creating an error by dividing a value by 0. As it is not an ArrayIndexOutOfBoundsException, next catch block handles the exception and prints the details. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“ArrayIndexOutOfBoundsException thrown :” + e); }catch (Exception e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Handling Multiple Exceptions Using Multiple Catch Blocks In this code segment, we”re showing how to use another example of multiple try/catch statements. In this example, we”re creating an error by dividing a value by 0 and handling it using ArithmeticException. Example package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArithmeticException e) { System.out.println(“ArithmeticException thrown :” + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“ArrayIndexOutOfBoundsException thrown :” + e); }catch (Exception e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output ArithmeticException thrown :java.lang.ArithmeticException: / by zero Out of the block Handling Multiple Exceptions Within A Single Catch Block Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it − Syntax catch (IOException|FileNotFoundException ex) { logger.log(ex); throw ex; Example Here is code segment showing how to use multiple catch in a single statement. In this example, we”re creating an error by dividing a value by 0. In single statement, we”re handling ArrayIndexOutOfBoundsException and ArithmeticException. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; int b = 0; int c = 1/b; System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println(“Exception thrown :” + e); } System.out.println(“Out of the block”); } } Output Exception thrown :java.lang.ArithmeticException: / by zero Out of the block Print Page Previous Next Advertisements ”;
Java – Enhanced @Deprecated Annotation ”; Previous Next @Deprecated annotation was introduced in java 5 version. A program element annotated with @Deprecated means it should not be used for any of the following reasons − Its usage may leads to errors. It may be incompatible in future version. It may be removed in future version. A better and efficient alternative has superseeded it. Compiler generates warnings whenever a deprecated element is used. With Java 9, two new enhancements are made to @Deprecated annotation. forRemoval − Indicates whether the annotated element is subject to removal in a future version. The default value is false. since − Returns the version in which the annotated element became deprecated. The default value is the empty string. Deprecated with since Following example of Boolean class javadoc on Java 9 illustrate the use of since attribute on @Deprecated annotation. Boolean Class Deprecated with forRemoval Following example of System class javadoc on Java 9 illustrate the use of forRemoval attribute on @Deprecated annotation. System Class Print Page Previous Next Advertisements ”;
Java – Multiresolution Image API ”; Previous Next Multi-resolution image API was introduced in Java 9. This API supports multiple images with different resolution variants. This API allows a set of images with different resolution to be used as a single multi-resolution image. Consider the following images. These are three images of a logo with different sizes. Now in order to work with these three images, Java 9 onwards, Multi-resolution Image API can be used as single API to get all variants or a particular variant to be displayed. // read all images into one multiresolution image MultiResolutionImage multiResolutionImage = new BaseMultiResolutionImage(images.toArray(new Image[0])); Here MultiResolutionImage and BaseMultiResolutionImage classes are part of java.awt.image package. Following are major operations of multi-resolution image. Image getResolutionVariant(double destImageWidth, double destImageHeight) − Gets a specific image which is best variant to represent this logical image at the indicated size. List<Image> getResolutionVariants() − Gets a readable list of all resolution variants. Example – Get All variants In this example, we”ve loaded three images and store them in MultiResolutionImage. Then using getResolutionVariants() method, we”re checking all the available image variants in this multi-resolution image and printing it. package com.tutorialspoint; import java.awt.Image; import java.awt.image.BaseMultiResolutionImage; import java.awt.image.MultiResolutionImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; public class Tester { public static void main(String[] args) throws IOException, MalformedURLException { // prepare a list of urls of all images List<String> imgUrls = List.of(“http://www.tutorialspoint.com/java9/images/logo.png”, “http://www.tutorialspoint.com/java9/images/mini_logo.png”, “http://www.tutorialspoint.com/java9/images/large_logo.png”); // create a list of Image object List<Image> images = new ArrayList<Image>(); // Create image objects using image urls for (String url : imgUrls) { images.add(ImageIO.read(new URL(url))); } // read all images into one multiresolution image MultiResolutionImage multiResolutionImage = new BaseMultiResolutionImage(images.toArray(new Image[0])); // get all variants of images List<Image> variants = multiResolutionImage.getResolutionVariants(); System.out.println(“Total number of images: ” + variants.size()); // print all the images for (Image img : variants) { System.out.println(img); } } } Output Let us compile and run the above program, this will produce the following result − Total number of images: 3 BufferedImage@7ce6a65d: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 color space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3 has alpha = true isAlphaPre = false ByteInterleavedRaster: width =311 height = 89 #numDataElements 4 dataOff[0] = 3 BufferedImage@4c762604: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 color space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3 has alpha = true isAlphaPre = false ByteInterleavedRaster: width =156 height = 45 #numDataElements 4 dataOff[0] = 3 BufferedImage@2641e737: type = 6 ColorModel: #pixelBits = 32 numComponents = 4 color space =java.awt.color.ICC_ColorSpace@548ad73b transparency = 3 has alpha = true isAlphaPre = false ByteInterleavedRaster: width =622 height = 178 #numDataElements 4 dataOff[0] = 3 Example – Get Specific variant In this example, we”ve loaded three images and store them in MultiResolutionImage. Then using getResolutionVariant() method, we”re getting specific image variant as per the provided resolution in this multi-resolution image and printing it. In case resoltution is not exact match, this method returns the neares t resolution image. package com.tutorialspoint; import java.awt.Image; import java.awt.image.BaseMultiResolutionImage; import java.awt.image.MultiResolutionImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; public class Tester { public static void main(String[] args) throws IOException, MalformedURLException { // prepare a list of urls of all images List<String> imgUrls = List.of(“http://www.tutorialspoint.com/java9/images/logo.png”, “http://www.tutorialspoint.com/java9/images/mini_logo.png”, “http://www.tutorialspoint.com/java9/images/large_logo.png”); // create a list of Image object List<Image> images = new ArrayList<Image>(); // Create image objects using image urls for (String url : imgUrls) { images.add(ImageIO.read(new URL(url))); } // read all images into one multiresolution image MultiResolutionImage multiResolutionImage = new BaseMultiResolutionImage(images.toArray(new Image[0])); // get all variants of images List<Image> variants = multiResolutionImage.getResolutionVariants(); System.out.println(“Total number of images: ” + variants.size()); // get a resolution-specific image variant for each indicated size Image variant1 = multiResolutionImage.getResolutionVariant(156, 45); 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[%d,%d]: [%d,%d]”, 311, 89, variant2.getWidth(null), variant2.getHeight(null)); Image variant3 = multiResolutionImage.getResolutionVariant(622, 178); System.out.printf(“nImage for destination[%d,%d]: [%d,%d]”, 622, 178, variant3.getWidth(null), variant3.getHeight(null)); Image variant4 = multiResolutionImage.getResolutionVariant(300, 300); System.out.printf(“nImage for destination[%d,%d]: [%d,%d]”, 300, 300, variant4.getWidth(null), variant4.getHeight(null)); } } Output Let us compile and run the above program, this will produce the following result − Total number of images: 3 Image for destination[156,45]: [311,89] Image for destination[311,89]: [311,89] Image for destination[622,178]: [622,178] Image for destination[300,300]: [622,178] Print Page Previous Next Advertisements ”;
Java – Nashorn JavaScript
Java – Nashorn JavaScript Engine ”; Previous Next Nashorn JavaScript Engine Nashorn is a very powerful and performant Javascript Engine in Java. It was introduced in Java 8 to replace the existing javascript engine, Rhino. Nashorn engine is 2 to 10 times faster in performance than it earlier counterpart. It can directly compile the javascript code to the bytcode in memory. It utilizes the dyanamics features introduced in Java 7 to boost performance. Using Nashorn engine, we can execute JavaScript code in command line tools. We can embed a javascript code in Java file and call the javascript methods in java code base. We can call java methods in javascript as well using jjs. Execute JavaScript via Command Line Tools For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute javascript codes at console. jjs is a versatile tool, it can interpret a javascript file as well as javascript code snippet. We can use jjs to even call java methods in a javascript code. Example Interpreting js File Let”s first try to create and save the file sample.js in c:> JAVA folder. This sample.js file is having a single javascript statement to print “Hello World” on the console using print() method. sample.js print(”Hello World!”); Open console and use the following command. Here jjs will read the sample.js file, interpret the javascript code snippet and execute the code. C:JAVA>jjs sample.js It will produce the following output: Hello World! Let”s update the sample.js to have a javascript function to be called. sample.js function sayMessage(){ print(”Hello World!”); } sayMessage(); Open console and use the following command. C:JAVA>jjs sample.js It will produce the following output: Hello World! We can evaluate or execute a javascript code snippet using jjs directly as well. Execute JavaScript Directly in Command Prompt Open the console and type jjs and press enter button. jjs tool will open an interactive session. Once jjs session is open, we can execute a javascript code. Once done, type quit() and press enter button to exit the jjs interactive session and to return back to the command prompt. Example C:JAVA>jjs jjs> print(“Hello, World!”) Hello, World! jjs> quit() >> C:JAVA> Passing Arguments to jjs jjs uses a special construct arguments to store the command line arguments passed. See the example below: Open the console and use the following command. Example C:JAVA> jjs — a b c jjs> print(”letters: ” +arguments) letters: a,b,c jjs> quit() >> C:JAVA> Calling JavaScript from Java Java has a ScriptEngineManager class since Java 6, which can be used to load the javascript engine as ScriptEngine instance. Once engine is loaded in the java code, we can call eval() method to evaluate a JavaScript code in Java. We can even use Java variable(s) in javascript code snippet. Example Create the following Java program using any editor of your choice in, say, C:> JAVA. Java8Tester.java import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; import javax.script.ScriptException; public class Java8Tester { public static void main(String args[]) { // create the script engine manager ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); // load the Nashorn javascript engine ScriptEngine nashorn = scriptEngineManager.getEngineByName(“nashorn”); String name = “Mahesh”; Integer result = null; try { // call the javascript function, pass a java variable nashorn.eval(“print(”” + name + “”)”); // call the javascript function and get the result back in java result = (Integer) nashorn.eval(“10 + 2”); } catch(ScriptException e) { System.out.println(“Error executing script: “+ e.getMessage()); } System.out.println(result.toString()); } } Verify the Result Compile the class using javac compiler as follows − C:JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:JAVA>java Java8Tester It should produce the following result − Mahesh 12 Calling Java from JavaScript Using jjs tool, we can even call Java code in a Javascript code snippet. In following example, we”ve created a BigDecimal type first by using Java.type (”java.math.BigDecimal”). Once BigDecimal class is loaded, we can use its method within JavaScript code as shown below: Example Create and save sample.js in c:> JAVA folder. sample.js // import BigDecimal java class var BigDecimal = Java.type(”java.math.BigDecimal”); function calculate(amount, percentage) { // use the BigDecimal class instances to showcase BigDecimal calculations var result = new BigDecimal(amount).multiply(new BigDecimal(percentage)).divide( new BigDecimal(“100″), 2, BigDecimal.ROUND_HALF_EVEN); return result.toPlainString(); } var result = calculate(568000000000000000023,13.9); print(result); Open the console and use the following command. C:JAVA>jjs sample.js It should produce the following output − 78952000000000000003.20 Print Page Previous Next Advertisements ”;
Java – Module System
Java – Module System ”; Previous Next In Java 9, Module system was introduced to enhance Java code modularity. Module is an abstraction over package. This module system is also known as JPMS, Java Platform Module System. It is mostly referred as Modules. What is a Module? A module is a self-describing collection of code and data and has a name to identify it. It a new kind of programming component which can contains packages, configurations, resources specific to a particular functionality. A module is able to restrict access to packages it contains. By default, code in a package within a module is not visible to outside world, not even via reflection. Java platform is itself modularised from java 9 onwards. If we use the list-modules command to list the java modules, it will print the various modules java supports as following: C:UsersMahesh>java –list-modules [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] C:UsersMahesh> Here we can see, that jdk specific packages are in jdk module and library specific packages are in java module. Features of Java Module System With the Modules component, following enhancements has been added in Java 9 − A new optional phase, link time is introduced. This phase is in-between compile time and run time. During this phase, a set of modules can be assembled and optimized, making a custom runtime image using jlink tool. javac, jlink, and java have additional options to specify module paths, which further locate definitions of modules. JAR format updated as modular JAR, which contains module-info.class file in its root directory. JMOD format introduced, a packaging format (similar to JAR) which can include native code and configuration files. Declaring Module In order to declare a module, we need to create a module-info.java in root folder of the application. This file contains all the meta data or module descriptions. Example module-info.java module com.tutorialspoint.greetings { } Adding Dependent Modules We can declare dependencies of other modules in the module. For example, if we want to use com.tutorialspoint.util module then we can add the declaration as follows: Example module com.tutorialspoint.greetings { requires com.tutorialspoint.util; } Adding Optional Modules We can declare optional dependencies of other modules using static keyword in the module. For example, if we want to use com.tutorialspoint.logging module then we can add the declaration as follows: Example module com.tutorialspoint.greetings { requires com.tutorialspoint.util; requires static com.tutorialspoint.logging; } Adding Transitive Modules We can declare transitive dependencies of other modules using transitive keyword in the module. For example, if we want to use com.tutorialspoint.base module as dependency of com.tutorialspoint.util module then we can add the declaration as follows: Example module com.tutorialspoint.greetings { requires com.tutorialspoint.util; requires static com.tutorialspoint.logging; requires transitive com.tutorialspoint.base; } This means if a module wants to use com.tutorialspoint.greetings then that module is required to add com.tutorialspoint.base module as well in module declaration. Export Public Classes By default, no public class of a package of a module is exposed to outside world. In order to use the public class, we”ve to export it as shown below: Example module com.tutorialspoint.greetings { requires com.tutorialspoint.util; requires static com.tutorialspoint.logging; requires transitive com.tutorialspoint.base; exports com.tutorialspoint.greetings.HelloWorld; } Allow Reflection By default, no private member of a package of a module is accessible via reflection. In order to allow reflection to inspect the class or module, we”ve to use opens command as shown below: Example module com.tutorialspoint.greetings { requires com.tutorialspoint.util; requires static com.tutorialspoint.logging; requires transitive com.tutorialspoint.base; exports com.tutorialspoint.greetings.HelloWorld; opens com.tutorialspoint.greetings.HelloWorld; } If we need to allow complete module to be open for reflection, we can use open command as shown below: open module com.tutorialspoint.greetings { requires com.tutorialspoint.util; requires static com.tutorialspoint.logging; requires transitive com.tutorialspoint.base; exports com.tutorialspoint.greetings.HelloWorld; } Creating and Using Java Module Following the steps to create a module say com.tutorialspoint.greetings. Step 1 Create a folder C:>JAVAsrc. Now create a folder com.tutorialspoint.greetings which is same as the name of module we”re creating. Step 2 Create module-info.java in C:>JAVAsrccom.tutorialspoint.greetings folder with following code. module-info.java module com.tutorialspoint.greetings { } module-info.java is the file which is used to create module. In this step we”ve created a module named com.tutorialspoint.greetings. By convention this file should reside in the folder whose name is same as module name. Step 3 Add the source code in the module. Create Java9Tester.java in C:>JAVAsrccom.tutorialspoint.greetingscom tutorialspointgreetings folder with following code. Java9Tester.java package com.tutorialspoint.greetings; public class Java9Tester { public static void main(String[] args) { System.out.println(“Hello World!”); } } By convention, the source code of a module to lie in same directory which is the name of the module. Step 4 Create a folder C:>JAVAmods. Now create a folder com.tutorialspoint.greetings which is same as the name of module we”ve created. Now compile the module to mods directory. C:/ > JAVA > javac -d mods/com.tutorialspoint.greetings src/com.tutorialspoint.greetings/module-info.java src/com.tutorialspoint.greetings/com/tutorialspoint/greetings/Java9Tester.java Step 5 Let”s run the module to see the result. Run the following command. C:/>JAVA>java –module-path mods -m com.tutorialspoint.greetings/com.tutorialspoint.greetings.Java9Tester Here module-path provides the module location as mods and -m signifies the main module. It will print the following output on console. Hello World! Print Page Previous Next Advertisements ”;
Java – JIT Compiler
Java – Just-In-Time (JIT) Compiler ”; Previous Next Just-in-time (JIT) compiler is a compiler that is used by JVM internally to translate the hot spots in the byte code to machine-understandable code. The main purpose of JIT compiler is to do heavy optimizations in performance. Java-compiled code is targeted for JVM. A Java compiler, javac compiles the Java code into bytecode. Now JVM interprets this bytecode and executes it on the underlying hardware. In case of some code is to be executed again and again, JVM identifies the code as hotspots and compiles the code further using the JIT compiler to the native machine code level and reuses the compiled code whenever needed. Let”s first understand the difference between Compiled vs Interpreted language and how Java takes benefits of both approaches. Compiled Vs. Interpreted Languages Languages such as C, C++, and FORTRAN are compiled languages. Their code is delivered as binary code targeted at the underlying machine. This means that the high-level code is compiled into binary code at once by a static compiler written specifically for the underlying architecture. The binary that is produced will not run on any other architecture. On the other hand, interpreted languages like Python and Perl can run on any machine, as long as they have a valid interpreter. It goes over line-by-line over the high-level code, converting that into binary code. Interpreted code is typically slower than compiled code. For example, consider a loop. An interpreted will convert the corresponding code for each iteration of the loop. On the other hand, a compiled code will translate only one. Further, since interpreters see only one line at a time, they are unable to perform any significant code such as changing the order of execution of statements like compilers. Example We shall look into an example of such optimization below − Adding two numbers stored in memory: Since accessing memory can consume multiple CPU cycles, a good compiler will issue instructions to fetch the data from memory and execute the addition only when the data is available. It will not wait and in the meantime, execute other instructions. On the other hand, no such optimization would be possible during interpretation since the interpreter is not aware of the entire code at any given time. But then, interpreted languages can run on any machine that has a valid interpreter of that language. Is Java Compiled or Interpreted? Java tried to find a middle ground. Since the JVM sits in between the javac compiler and the underlying hardware, the javac (or any other compiler) compiler compiles Java code in the Bytecode, which is understood by a platform-specific JVM. The JVM then compiles the Bytecode in binary using JIT (Just-in-time) compilation, as the code executes. HotSpots In a typical program, there’s only a small section of code that is executed frequently, and often, it is this code that affects the performance of the whole application significantly. Such sections of code are called HotSpots. If some section of code is executed only once, then compiling it would be a waste of effort, and it would be faster to interpret the Bytecode instead. But if the section is a hot section and is executed multiple times, the JVM would compile it instead. For example, if a method is called multiple times, the extra cycles that it would take to compile the code would be offset by the faster binary that is generated. Further, the more the JVM runs a particular method or a loop, the more information it gathers to make sundry optimizations so that a faster binary is generated. Working of JIT Compiler JIT compiler helps in improving the Java programs execution time by compiling certain hotspot codes to machine or native code. JVM scans the complete code and identifies the hotspots or the code which is to be optimized by JIT and then invokes JIT Compiler at runtime in turn improves the efficiency of the program and runs it faster. As JIT compilation is a processor and memory-intensive activity, JIT compilation is to be planned accordingly. Compilation Levels JVM supports five compilation levels − Interpreter C1 with full optimization (no profiling) C1 with invocation and back-edge counters (light profiling) C1 with full profiling C2 (uses profiling data from the previous steps) Use -Xint if you want to disable all JIT compilers and use only the interpreter. Client Vs. Server JIT (Just-In-Time) Compiler Use -client and -server to activate the respective modes. The client compiler (C1) starts compiling code sooner than the server compiler (C2). So, by the time C2 has started compilation, C1 would have already compiled sections of code.But while it waits, C2 profiles the code to know about it more than C1 does. Hence, the time it waits if offset by the optimizations can be used to generate a much faster binary. From the perspective of a user, the trade-off is between the startup time of the program and the time taken for the program to run. If startup time is the premium, then C1 should be used. If the application is expected to run for a long time (typical of applications deployed on servers), it is better to use C2 as it generates much faster code which greatly offsets any extra startup time. For programs such as IDEs (NetBeans, Eclipse) and other GUI programs, the startup time is critical. NetBeans might take a minute or longer to start. Hundreds of classes are compiled when programs such as NetBeans are started. In such cases, the C1 compiler is the best choice. Note that there are two versions of C1 − 32b and 64b. C2 comes only in 64b. Examples of JIT Compiler Optimizations Following examples showcases JIT Compiler Optimizations: Example of JIT optimization in case of objects Let us consider the following code − for(int i = 0 ; i <= 100; i++) { System.out.println(obj1.equals(obj2)); //two objects } If this code is interpreted, the interpreter would deduce for each iteration that classes