Monday, September 12, 2022

Spring Boot – Difference Between AOP and OOP

Spring Boot, AOP, OOP, Oracle Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java Tutorial and Materials, Java Prep, Java Preparation

AOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business logic. It is more convenient to use because changes need to be done in only one place. AOP is used along with spring Ioc to provide a very capable middleware solution.

Note: Cross cutting concerns are one of the concerns in any application such as logging, security, caching, etc. They are present in one part of the program but they may affect other parts of the program too.

Spring Boot, AOP, OOP, Oracle Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java Tutorial and Materials, Java Prep, Java Preparation
AOP is used along with Oop as it also works around classes and objects, etc. We can also say that Oop is a basic term for AOP. Different Frameworks used in Aop are AspectJ, JBoss, and Spring. AOP makes the program loosely coupled. AOP separates business logic from cross-cutting concerns. The aspect class which contains cross-cutting concerns is annotated by @Aspect and @EnableAspectJAutoProxy annotations

AOP has different terms like Aspect, Weaving, different types of advices, JoinPoints and Pointcut expressions, etc. These terms are explained below:

◉ Aspect: The cross-cutting concerns are modularized as Aspect. The classes which contain such cross-cutting concerns are annotated with @Aspect annotation.
◉ Join point: Method execution is represented by using Joinpoint.
◉ Advice: Aspect takes action on a particular Joinpoint. This action depends on various advice which is explained below:
◉ Before advice: It runs before the method execution.
◉ After returning advice: It runs after the result is returned by the method.
◉ After throwing advice: It runs after an exception is thrown by the method.
◉ After (finally) advice: It is executed after method execution or after an exception is thrown or the result is returned by the method.
◉ Around advice: It can perform the behavior before and after the method invocation.
◉ Pointcut: Pointcut is a signature that matches the join points.

Illustration: A pointcut expression with before advice:

// Annotation
@Before("execution(* abc.efg.gettingstarted.dao.*.add(..))")

public void allMethods(Point Point) 
{  // Aspect body }

Object-Oriented Programming


The object-oriented programming model works around classes and objects. The main building blocks of Oop are classes, objects, methods, attributes, etc. Oop has various advantages such as code reusability, flexibility, etc. It also maintains modularity using classes.

Note: Object is an instance of class and class is a blueprint of an object created.

The Key unit of Modularity(breaking of code into different modules) in Object-Oriented Programming is class. Oop contains objects, classes, interfaces, etc. Oop lacks the feature of using cross-cutting concerns. It consists of various concepts such as Data abstraction, Encapsulation, Polymorphism, and Inheritance.

Illustration: If there is a fruit class then apple, orange, banana are various objects of the fruit class.

Source: geeksforgeeks.org

Friday, September 9, 2022

7 Best Plugins For Spring Boot and Java in Eclipse

With the fast-paced technology, every developer wants to build something which requires less time and effort. Being in one of the most growing communities with a count of more than 10 million, developers have to maintain that by working more efficiently. The best plugin you use for your project, the more efficient an application is. Like Python which has uncountable libraries used to build an application, Java has plugins that can be installed in Eclipse to boost productivity and add extra functionalities to the application. Plugins are the smallest, deployable and extensible libraries that contain pieces of code meant for some specific purpose. 

Oracel Java, Oracle Java Tutorial and Materials, Core Java, Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java News, Java Prep, Java Preparation

How to install plugins in your IDE (Eclipse)? The answer is using the marketplace in Eclipse. Eclipse marketplace has provided you with the feature to search for a plugin and its download count in the IDE itself. Eclipse has 1667 plugins available for Spring Boot and Java development. Having too many plugins creates confusion as to which one to choose. We have filtered some of the best plugins which you can use for SpringBoot and Java in Eclipse. Let’s explore them one by one. 

1. EGit

EGit (an Eclipse provider for Git) is one of the best plugins for Java developers. As many of us know that Git is an open-source version control system where every developer can manage and update changes to the source code of the website. When using Eclipse for implementing software, EGit is an essential tool that can be used by developers to perform operations like branching and reverting a single file. This plugin provides rebasing and has streamlined commands to pull/push, synchronize view, support, and read for . git/exclude files. It has multiple views to perform Git actions without knowing git commands.

Features of EGit:

◉ Creating backup is easy

◉ Track and update changes

◉ Git repository cloning to pull, push, merge, commit, etc

2. SonarLint

SonarLint is a free plugin for Eclipse that is primarily responsible for detecting and fixing quality and security issues while writing code. It provides instant feedback on the problems faced in the code during development supporting multiple languages other than Java such as JavaScript, PHP, and Python. Additionally, SonarLint can also be integrated with SonarQube or SonarCloud. SonarLint is used by developers to analyze code, detect errors/bugs, and act as a quality editor. 

Features of SonarLint:

◉ Big picture of all issues

◉ Secure, reliable, and maintainable

◉ Find logs wherever needed (Bug detection)

◉ Solves previous issues

3. TestNG

TestNG is an excellent plugin for Eclipse. Developers use it to perform unit, end-to-end, functional, and integration testing for Java projects. After performing tests, all errors found are reported in a new tab which helps you to fix issues efficiently. Also, it contains several templates to create easily. It comes with additional functionalities like data-driven testing, flexible test configuration, and execution models, and has default JDK functions for runtime and logging. If you’re new to Eclipse and don’t know how to install it, here you go – How to Install TestNG on Eclipse IDE?

Features of TestNG:

◉ Dependent groups, methods

◉ Multithreaded execution

◉ Uses more Java and Object-Oriented features

4. ADT (Android Development Tool)

Android Development Tool is an Eclipse plugin designed for Java developers with the intention to provide a robust and integrated environment to build android applications. It lets you perform tasks such as creating an application UI, adding packages on the basis of framework, and debugging applications. Java Programming Foundation – Self-Paced will help you ace the Java trends and will guide you with all the technical concepts. 

Features of ADT:

◉ Powerful and integrated plugin

◉ Custom XML editors

◉ Ability to customize extensively

◉ Supports multiple operating systems

5. Spring Tools

Spring Tool is the most popular Java plugin in Eclipse used to create Spring Boot projects. This plugin comes with tools used to run and monitor apps from inside IDE. You can also navigate through spring-specific code completion. It eases the development of applications by integrating Spring Boot with Initalzr. Having integration with Cloud Foundry, this plugin helps you to make it a perfect plugin for microservice development. The latest version used by Java developers is Spring Boot 4.

Features of Spring Tools:

◉ Provides you with run-time information

◉ Fast and productive

◉ Flexible plugin

◉ Secure and productive

6. EclEmma Java Code Coverage

Oracel Java, Oracle Java Tutorial and Materials, Core Java, Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java News, Java Prep, Java Preparation
EclEmma, with its latest version 3.1.6 is available at the Eclipse marketplace is a free code coverage tool for Eclipse. It mainly focuses on supporting the individual developer in an interactive way. It was inspired by the great EMMA library which is developed by Vlad Roubtsov. It helps in faster development, also when the execution is done, it highlights the coverage results with different colors indicating different statuses. 

Features of EclEmma:

◉ Testing(JUnit, TestNG, SWTBOt)

◉ Analysis of code coverage

◉ Allows you to export/import files

◉ Speeds up your development

7. JRebel for Eclipse

JRebel is a tool used for productivity by developers to instantly reload code changes. It helps Java developers to create awesome applications very fast and gives them a high ROI productivity solution. It skips the rebuild, restart, and redeploy cycle common in Java development. It is easy to install and supports the majority of real-world enterprise Java stacks.

Features ofJRebel:

◉ Maintains state of the application

◉ Dedicated integration

◉ Visible real-time change

◉ Integrates with your stack seamlessly

Source: geeksforgeeks.org

Thursday, September 8, 2022

Inspect the contents of the Java Metaspace region

JVM Memory has following regions:

a. Young Generation

b. Old Generation

c. Metaspace

d. Others region

Oracle Java, Java Tutorial and Materials, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Core Java, Oracle Java Prep, Oracle Java Preparation, Oracle Java News

To see what objects are stored in what region, you may refer to this video clip. Sometimes your application might run into ‘java.lang.OutOfMemoryError: Metaspace’ as discussed in this post. In such circumstances you might want to see what are the Contents loaded in the Metaspace region of the JVM. In nutshell, the Metaspace region in the JVM memory contains the class metadata definitions that are required to execute your application. If you want to understand what class metadata definitions means, you can refer to this documentation. It has intense details, you may not have to understand all the details of it. Basically if you can understand what are the classes that are loaded into memory, it will give a good idea what are the Contents that are present in the Metaspace region of the JVM memory. In this post let’s explore the options that are available to see the classes that are loaded into the Metaspace.

Below are the options to see the classes that are loaded in the Metaspace:

1. -verbose:class

2. -Xlog:class+load

3. jcmd GC.class_histogram

4. Programmatic approach

5. Heap Dump analysis

Let’s discuss each option in detail in this post.

1. -verbose:class


If you are running on Java version 8 or below then you can use this option. When you pass the ‘-verbose:class’ option to your application during startup, it will print all the classes that are loaded into memory. Loaded classes will be printed in the standard error stream (i.e. console, if you aren’t routing your error stream to a log file).

java {app_name} -verbose:class

Following is the sample output of the open source BuggyApp program when ‘-verbose:class’ argument is passed:

[Opened C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Object from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.io.Serializable from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Comparable from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.CharSequence from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.String from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.reflect.AnnotatedElement from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.reflect.GenericDeclaration from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.reflect.Type from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Class from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Cloneable from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.ClassLoader from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.System from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Throwable from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Error from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.ThreadDeath from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.Exception from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.RuntimeException from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.SecurityManager from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.security.ProtectionDomain from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.security.AccessControlContext from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.security.SecureClassLoader from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.ReflectiveOperationException from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.ClassNotFoundException from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.LinkageError from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.NoClassDefFoundError from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.ClassCastException from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.ArrayStoreException from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.VirtualMachineError from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.OutOfMemoryError from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]
[Loaded java.lang.StackOverflowError from C:\Program Files\Java\jre1.8.0_171\lib\rt.jar]

2. -Xlog:class+load


If you are running on Java version 9 or above then you can use this option. When you pass the ‘-Xlog:class+load’ option to your application during startup, it will print all the classes that are loaded into memory. Loaded classes will be printed in the file path you have configured.

java {app_name} -Xlog:class+load=info:/opt/log/loadedClasses.txt

Following is the sample output of a java program when ‘-Xlog:class+load’ argument is passed:

[0.004s][info][class,load] opened: /home/ec2-user/jdk-9.0.4/lib/modules
[0.006s][info][class,load] java.lang.Object source: jrt:/java.base
[0.007s][info][class,load] java.io.Serializable source: jrt:/java.base
[0.007s][info][class,load] java.lang.Comparable source: jrt:/java.base
[0.007s][info][class,load] java.lang.CharSequence source: jrt:/java.base
[0.007s][info][class,load] java.lang.String source: jrt:/java.base
[0.007s][info][class,load] java.lang.reflect.AnnotatedElement source: jrt:/java.base
[0.007s][info][class,load] java.lang.reflect.GenericDeclaration source: jrt:/java.base
[0.007s][info][class,load] java.lang.reflect.Type source: jrt:/java.base
[0.008s][info][class,load] java.lang.Class source: jrt:/java.base
[0.008s][info][class,load] java.lang.Cloneable source: jrt:/java.base
[0.008s][info][class,load] java.lang.ClassLoader source: jrt:/java.base
[0.008s][info][class,load] java.lang.System source: jrt:/java.base
[0.008s][info][class,load] java.lang.Throwable source: jrt:/java.base
[0.008s][info][class,load] java.lang.Error source: jrt:/java.base
[0.008s][info][class,load] java.lang.ThreadDeath source: jrt:/java.base
[0.008s][info][class,load] java.lang.Exception source: jrt:/java.base
[0.008s][info][class,load] java.lang.RuntimeException source: jrt:/java.base
[0.008s][info][class,load] java.lang.SecurityManager source: jrt:/java.base
[0.008s][info][class,load] java.security.ProtectionDomain source: jrt:/java.base
[0.009s][info][class,load] java.security.AccessControlContext source: jrt:/java.base
[0.009s][info][class,load] java.security.SecureClassLoader source: jrt:/java.base
[0.009s][info][class,load] java.lang.ReflectiveOperationException source: jrt:/java.base
[0.009s][info][class,load] java.lang.ClassNotFoundException source: jrt:/java.base
[0.009s][info][class,load] java.lang.LinkageError source: jrt:/java.base
[0.009s][info][class,load] java.lang.NoClassDefFoundError source: jrt:/java.base
[0.009s][info][class,load] java.lang.ClassCastException source: jrt:/java.base
[0.009s][info][class,load] java.lang.ArrayStoreException source: jrt:/java.base
[0.009s][info][class,load] java.lang.VirtualMachineError source: jrt:/java.base
[0.009s][info][class,load] java.lang.OutOfMemoryError source: jrt:/java.base
[0.009s][info][class,load] java.lang.StackOverflowError source: jrt:/java.base
[0.009s][info][class,load] java.lang.IllegalMonitorStateException source: jrt:/java.base
[0.009s][info][class,load] java.lang.ref.Reference source: jrt:/java.base
[0.009s][info][class,load] java.lang.ref.SoftReference source: jrt:/java.base
[0.009s][info][class,load] java.lang.ref.WeakReference source: jrt:/java.base
[0.009s][info][class,load] java.lang.ref.FinalReference source: jrt:/java.base
[0.009s][info][class,load] java.lang.ref.PhantomReference source: jrt:/java.base
[0.009s][info][class,load] java.lang.ref.Finalizer source: jrt:/java.base
[0.009s][info][class,load] java.lang.Runnable source: jrt:/java.base
[0.009s][info][class,load] java.lang.Thread source: jrt:/java.base
[0.009s][info][class,load] java.lang.Thread$UncaughtExceptionHandler source: jrt:/java.base
[0.009s][info][class,load] java.lang.ThreadGroup source: jrt:/java.base
[0.010s][info][class,load] java.util.Map source: jrt:/java.base
[0.010s][info][class,load] java.util.Dictionary source: jrt:/java.base
[0.010s][info][class,load] java.util.Hashtable source: jrt:/java.base
[0.010s][info][class,load] java.util.Properties source: jrt:/java.base
[0.010s][info][class,load] java.lang.Module source: jrt:/java.base
[0.010s][info][class,load] java.lang.reflect.AccessibleObject source: jrt:/java.base

3. jcmd GC.class_histogram


JDK contains a tool called ‘jcmd’. You can invoke this tool when JVM is running to inspect the Contents of the Metaspace region. When you invoke this tool with ‘GC.class_histogram’ argument, it will print the list of classes that are loaded into the memory.  You can invoke this tool in two modes:

a. Print loaded classes on the console

jcmd {pid} GC.class_histogram

When you invoke the ‘jcmd’ as shown above it will print all the loaded classes in the console. Here {pid} is the process id of your java application. 

b. Print loaded classes on a File

jcmd {pid} GC.class_histogram filename={file-path}

When you invoke the ‘jcmd’ as shown above, it will print all the loaded classes in the file path specified in the ‘filename’ argument. Here {pid} is the process id of your java application.

Here is a blog post which helps you to identify the process id quickly.

Following is the sample output of the open source BuggyApp program when ‘jcmd GC.class_histogram’ argument is passed:

jcmd 19684 GC.class_histogram
19684:
 
 num     #instances         #bytes  class name
----------------------------------------------
   1:        143036       75523008  [Ljavassist.bytecode.ConstInfo;
   2:        718060       70032224  [C
   3:       1573553       50353696  java.util.HashMap$Node
   4:        430124       24732832  [Ljava.lang.Object;
   5:       1001290       24030960  javassist.bytecode.Utf8Info
   6:        858268       20598432  java.util.ArrayList
   7:        718037       17232888  java.lang.String
   8:        144011       14987488  java.lang.Class
   9:        143081       11447152  [Ljava.util.HashMap$Node;
  10:        143036        9154304  javassist.bytecode.ClassFile
  11:        143035        9154240  javassist.CtNewClass
  12:        286124        6892400  [B
  13:        143085        6868080  java.util.HashMap
  14:        286078        6865872  javassist.bytecode.ClassInfo
  15:        143036        6865728  [[Ljavassist.bytecode.ConstInfo;
  16:        143049        5721960  javassist.bytecode.MethodInfo
  17:        143042        5721680  javassist.bytecode.CodeAttribute
  18:        143323        4586336  java.util.Hashtable$Entry
  19:        143038        4577216  java.lang.ref.WeakReference
  20:        143036        4577152  javassist.bytecode.ConstPool
  21:        143045        3433080  javassist.bytecode.MethodrefInfo
  22:        143045        3433080  javassist.bytecode.NameAndTypeInfo
  23:        143042        3433008  javassist.bytecode.ExceptionTable
  24:        143036        3432864  javassist.bytecode.LongVector
  25:        143036        3432864  javassist.bytecode.SourceFileAttribute
  26:        143622        2323336  [I
  27:            10         788688  [Ljava.util.Hashtable$Entry;
  28:           642          20544  java.util.concurrent.ConcurrentHashMap$Node
  29:           244          13664  java.lang.invoke.MemberName
  30:           341          10912  sun.misc.FDBigInteger
  31:           212           8480  java.lang.ref.SoftReference
  32:           140           8400  [Ljava.lang.ref.SoftReference;
  33:           234           7488  java.lang.invoke.LambdaForm$Name
  34:           176           7040  java.lang.invoke.MethodType
  35:           256           6144  java.lang.Long
  36:            16           6016  java.lang.Thread
  37:           173           5880  [Ljava.lang.Class;
  38:           366           5856  java.lang.Object
  39:           177           5664  java.lang.invoke.MethodType$ConcurrentWeakInternSet$WeakEntry
  40:            10           5280  [Ljava.util.concurrent.ConcurrentHashMap$Node;
  41:           256           4096  java.lang.Byte
  42:           256           4096  java.lang.Integer
  43:           256           4096  java.lang.Short
  44:            73           4088  java.lang.invoke.MethodTypeForm
  45:            82           3808  [Ljava.lang.invoke.LambdaForm$Name;
  46:            77           3696  java.lang.invoke.LambdaForm

4. Programmatic approach


You can also use a programmatic approach to print the classes that are loaded into the memory. Open source Guava library provides APIs to print the loaded classes. Below is the code sample that leverage Guava library to print the loaded classes in the memory:

ClassPath classPath = ClassPath.from(BuggyAppLoader.class.getClassLoader());
Set<ClassInfo> classes = classPath.getAllClasses();
for(ClassInfo classInfo : classes) {
    logger.info(classInfo.getName());
}

org.apache.catalina.core.AsyncContextImpl
org.apache.catalina.core.AsyncListenerWrapper
org.apache.catalina.core.Constants
org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor
org.apache.catalina.core.ContainerBase$PrivilegedAddChild
org.apache.catalina.core.ContainerBase$StartChild
org.apache.catalina.core.ContainerBase$StartStopThreadFactory
org.apache.catalina.core.ContainerBase$StopChild
org.apache.catalina.core.ContainerBase
org.apache.catalina.core.DefaultInstanceManager$1
org.apache.catalina.core.DefaultInstanceManager$2
org.apache.catalina.core.DefaultInstanceManager$3
org.apache.catalina.core.DefaultInstanceManager$AnnotationCacheEntry
org.apache.catalina.core.DefaultInstanceManager$AnnotationCacheEntryType
org.apache.catalina.core.DefaultInstanceManager
org.apache.catalina.core.JreMemoryLeakPreventionListener
org.apache.catalina.core.NamingContextListener
org.apache.catalina.core.StandardContext$1
org.apache.catalina.core.StandardContext$ContextFilterMaps
org.apache.catalina.core.StandardContext$NoPluggabilityServletContext
org.apache.catalina.core.StandardContext
org.apache.catalina.core.StandardContextValve
org.apache.catalina.core.StandardEngine$AccessLogListener
org.apache.catalina.core.StandardEngine$NoopAccessLog
org.apache.catalina.core.StandardEngine
org.apache.catalina.core.StandardEngineValve
org.apache.catalina.core.StandardHost$1
org.apache.catalina.core.StandardHost$MemoryLeakTrackingListener
org.apache.catalina.core.StandardHost
org.apache.catalina.core.StandardHostValve
org.apache.catalina.core.StandardPipeline
org.apache.catalina.core.StandardServer
org.apache.catalina.core.StandardService
org.apache.catalina.core.StandardThreadExecutor
org.apache.catalina.core.StandardWrapper
org.apache.catalina.core.StandardWrapperFacade
org.apache.catalina.core.StandardWrapperValve
org.apache.catalina.core.ThreadLocalLeakPreventionListener

5. Heap Dump analysis


Another option to see the classes that are loaded into memory is to inspect Heap Dump. Heap dump reports all the data, objects, classes that are loaded into memory. You can use one of the approaches given here to capture the heap dump. Once a heap dump is captured, you can use the heap dump analysis tools such as Eclipse MAT, HeapHero,… to analyze the heap dump.

Below is the excerpt from the report generated by the HeapHero tool that shows the classes that are loaded into the memory.

Oracle Java, Java Tutorial and Materials, Oracle Java Career, Oracle Java Skills, Oracle Java Jobs, Core Java, Oracle Java Prep, Oracle Java Preparation, Oracle Java News

Note: All the approaches mentioned above will not add noticeable overhead to your application, however the heap dump approach is an intrusive option and it will add considerable overhead to your application. When heap dump is captured your application will be paused until capturing is complete.

Source: javacodegeeks.com

Friday, August 26, 2022

Quiz yourself: Controlling the number of instances of a class

Which is the best approach: singletons, sealed classes, abstract classes, final classes, or enums?

Imagine that your design requires exactly four instances of a particular class.

Quiz Yourself, Oracle Java, Java Tutorial and Materials, Java Certification, Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation

Which approach best provides for this need? Choose one.

A. Singletons

B. Sealed classes

C. Abstract classes

D. Final classes

E. Enums

Answer. Option A is incorrect because singleton is not a Java keyword, nor is it a concept defined in the Java Language Specification. Singleton is actually the name of a design pattern and as a design pattern, it can be implemented in several different ways.

From the perspective of this question, the most important characteristic of a singleton is that it limits the number of instances of its type to one per JVM. The quiz question simply requires that the number of instances be fixed; it does not require that number to be one, and as such, an approach is necessary that allows the instance count to be greater than one. Consequently, option A is incorrect.

Option B is also incorrect. Sealed classes were added in Java 17, and the feature’s goal is to fix a set of types that exist as specializations of a particular type. For example, you could specify that a class RoadTransport is permitted to have only subtypes Car, Truck, Bus, Motorcycle, and Bicycle. Note that the sealed classes feature does not limit the number of instances of these classes that can exist.

In addition, option C is incorrect. Abstract classes are a mechanism to capture the common functionality that’s shared by several types in a single class, and they require developers to add specific additional functionality to subclasses. As a side note, an abstract class can be sealed, but as before, this does not have an impact on the number of instances you can create.

Option D is also incorrect. The final modifier, when applied to a class, means you cannot subclass that class. However, the modifier does not imply any control on the number of instances.

Option E is correct, because an enum type provides a clear, language-supported solution to control the number of instances of a class. There are some limitations on enum types; notably, the parent class of an enum is always java.lang.Enum, though an enum can implement interfaces of your choosing.

A second limitation is that an enum is always a final class and cannot be subclassed. This is important, since instances of a subclass are also instances of their parents, and if subclassing were possible, those subclasses would break the contract of a fixed number of instances.

It’s worth mentioning that a programmer can tightly control the construction of any class, and with it the number of instances of such a class, by marking all the constructors of that class as private and providing access to instances through a factory method. In fact, this idea is essential to the implementation of both Java’s enum type and the Singleton design pattern. However, because this approach is not an option for this question, it’s not a correct answer here.

Conclusion. The correct answer is option E.

Source: oracle.com

Wednesday, August 24, 2022

The arrival of Java 17!

Oracle is proud to announce the general availabilty of JDK 17. This release is the eighth Feature Release delivered on time through the six-month release cadence. This level of predictability allows developers to easily manage their adoption of innovation thanks to s steady stream of expected changes.

Java 17, Oracle Java Exam Prep, Oracle Java Prep, Oracle Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java Preparation Exam

Java’s ability to boost performance, stability, and security continues to make it the world’s most popular programming language. According to an IDC report over ten million developers, representing 75% of full-time developers worldwide, use Java, more than any other language.

JDK 17 is now available!


Oracle now offers JDK 17 for developers, end-users, and enterprises. As an LTS release, Oracle JDK 17 will receive performance, stability and security updates for at least 8 years following the Oracle Critical Patch Update (CPU) schedule as outlined in the Oracle Java SE Support Roadmap.

Oracle JDK 18, the next six month cadence release is now scheduled for in March 2022.

Java 17 is the second long-term support (LTS) under the release cadence announced in 2018. Oracle has announced plans to shorten the time between future LTS releases, from 3 years to 2 years so you should expect the next LTS to be Java 21 in September of 2023.

Another important change with Oracle JDK 17 is new simple license terms which will allow companies to use Oracle JDK 17, including the quarterly performance, stability, and security patches, at no cost for at least the next three years, allowing one full year of overlap with the next LTS release. Java SE Subscribers get access to Oracle’s Java SE Support and commercial features such as GraalVM Enterprise, Java Management Service and the Advanced Management Console.

Java 17, Together


As with previous release, with Java 17, we continue to celebrate the contributions from many individuals and organizations in the OpenJDK Community — we all build Java, together!

JDK 17 Fix Ratio


The rate of change over time in the JDK releases has remained largely constant for years, but under the six-month cadence the pace at which production-ready features and improvements are delivered has vastly improved.

Instead of making tens of thousands of fixes and delivering close to one hundred JEPs (JDK Enhancement Proposals) every few years as we did with yesteryear Major Releases, enhancements are delivered in leaner Feature Releases on a more manageable, predictable six-month schedule. The changes range from significant new features to small enhancements to routine maintenance, bug fixes, and documentation improvements. Each change is represented in a single commit for a single issue in the JDK Bug System.

Of the 12,733 JIRA issues marked as fixed in Java 12 through Java 17 at the time of their GA, 9,218 were completed by people working for Oracle while 3,515 were contributed by individual developers and developers working for other organizations.

In Java 17, of the 2,645 JIRA issues marked as fixed, 1,774 were completed by Oracle, while 871 were contributed by other members of the Java community. Going through the issues and collating the organization data from assignees results in the following chart of organizations sponsoring the development of contributions in Java 17:

Java 17, Oracle Java Exam Prep, Oracle Java Prep, Oracle Java Certification, Oracle Java Career, Java Skills, Java Jobs, Java Preparation Exam

Oracle would like to thank the developers working for organizations like Amazon, NTT Data, Red Hat, SAP and Tencent for their notable contributions.  We are also thankful to see contributions from smaller organizations such as Bellsoft, DataDog, Loongson, Skymatic and independent developers who collectively contributed 6% of the fixes in Java 17.

We are equally grateful to the many experienced developers who reviewed proposed changes, the early adopters who tried out early access builds and reported issues, and the dedicated professionals who provided feedback on the OpenJDK mailing lists. 

The following individuals provided invaluable feedback on build quality, logged good quality bugs, or offered frequent updates:

◉ Jaikiran Pai (Apache Ant)
◉ Rick Hillegas (Apache Derby)
◉ Uwe Schindler (Apache Lucene)
◉ Mark Thomas (Apache Tomcat)
◉ Martin Grigorov (Apache Tomcat, Apache Wicket)
◉ Rafael Winterhalter (Byte Buddy)
◉ Yoann Rodière (Hibernate ORM, Validator, Search, Reactive)
◉ Marc Hoffman (JaCoCo)
◉ Lukas Eder (jOOQ)
◉ Christian Stein (JUnit 5)
◉ David Karnok (RxJava)

Additionally, through the Quality Outreach program we would like to thank the following FOSS projects and individuals who provided excellent feedback on testing Java 17 early access builds to help improve the quality of the release.

◉ Apache Aries Spi Fly
◉ Apache CXF
◉ Apache Zookeeper (Enrico Olivelli)
◉ Aries JAX-RS
◉ BurningWave
◉ DataSketches
◉ Eclipse Collections
◉ Eo-yaml
◉ FXGL
◉ JabRef
◉ JaCoCo (Evgeny Mandikov)
◉ Java Katas (Chandra Guntur)
◉ Jenkins
◉ Jobrunr
◉ JOOQ
◉ JUnit
◉ Karate
◉ MyBatis (Iwao Ave)
◉ Netty
◉ PDFsam
◉ Sedja
◉ Selenide
◉ Syncope
◉ Vaadin

New in Java 17


Along with thousands of performance, stability and security updates, Java 17 delivers fourteen enhancements/changes (known as JDK Enhancement Proposals - JEPs), including three delivered in incubator modules and one preview language feature.

Incubator modules allow putting non-final APIs and non-final tools in the hands of developers and users to gather feedback that will ultimately improve the quality of the Java platform.

Similarly, Preview Features are fully specified and fully implemented Language or VM Features of the Java SE Platform; and yet impermanent. They are made available in JDK Feature Releases to allow for developer feedback based on real-world uses, before them becoming permanent in a future release.  This also affords tool vendors the opportunity to work towards supporting features before they are finalized into the Java SE Standard.

We’ve grouped the fourteen JEPs delivered with Java 17 into seven categories:

1. Language Feature

JEP 409: Sealed Classes

Sealed Classes allow API designers to specify which classes or interfaces may extend or implement a given class. Having an exhaustive list of cases to consider when modeling a problem can simplify development. JEP 409 was developed in the OpenJDK Project Amber, which aims to continually improve developer productivity through evolution of the Java programming language.

2. Updates and Improvements on Core Libraries

JEP 306: Restore Always-Strict Floating-Point Semantics

The Java programming language and Java virtual machine originally only had strict floating-point semantics. Starting in JDK 1.2, small variances in those strict semantics were allowed by default to accommodate limitations of then-current hardware architectures. Those variances are no longer helpful or necessary and have been removed by JEP 306.

JEP 356: Enhanced Pseudo-Random Number Generator

Updates to java.util.random improve the interoperability of different PRNGs (Pseudo-Random Number Generators) and make it easy to request an algorithm based on requirements rather than hard coding a specific implementation.  Changes include new interface types and implementations for pseudorandom number generators (PRNGs), including jumpable PRNGs and an additional class of splitable PRNG algorithms (LXM) and a new RandomGeneratorFactory class.

JEP 382: New macOS Rendering Pipeline

This new pipeline reduces the JDK’s dependency on the deprecated Apple OpenGL API by implementing a Java 2D rendering pipeline for macOS using the new Apple Metal API.

JEP 415: Context-Specific Deserialization Filters

Filter Incoming Serialization Data, added with JDK 9 (JEP 290), is improved by allowing applications to configure context-specific and dynamically-selected deserialization filters via a JVM-wide filter factory that is invoked to select a filter for each individual deserialization operation. This makes it possible to take advantage of deserialization filters without requiring every stream’s creator to update their code or making the filter too restrictive or too permissive.

3. New Platform Support

JEP 391: macOS AArch 64 Port

Delivers a version of the JDK for macOS that runs natively on Apple’s newer Arm 64 based systems.

4. Previews and Incubators

JEP 406: Pattern Matching for switch (Preview)

Enhances the Java programming language allowing pattern matching to be tested within a switch statement or switch expression. Using pattern matching in switch complex data-oriented queries can be expressed concisely and safely. JEP 406 was developed in the OpenJDK Project Amber.

JEP 412: Foreign Function and Memory API (Incubator)

Improves APIs introduced with JDK 14 and JDK 15 through which Java programs can interoperate with code and data outside of the Java runtime. By efficiently invoking foreign functions (i.e., code outside the JVM), and by safely accessing foreign memory (i.e., memory not managed by the JVM), the API enables Java programs to call native libraries and process native data without the brittleness and danger of JNI. JEP 412 was developed in the OpenJDK Project Panama which aims to simplify the interaction between Java code and foreign (non-Java) APIs.

JEP 414: Vector API (Second Incubator)

Enhances APIs that allow expressing vector computations in a way that will reliably compile at runtime to optimal vector instructions on supported CPU architectures. Vector operations can deliver performance superior to equivalent scalar computations and are quite common in fields such as Machine Learning, Artificial Intelligence, and Cryptography. JEP 412 was developed in the OpenJDK Project Panama.

5. Future Proofing Java Programs

JEP 403: Strongly Encapsulate JDK Internals

It will no longer be possible to relax the strong encapsulation of internal elements through a single command-line option, as was possible in JDK 9 through JDK 16 This change hides by default all but a few critical internal APIs such as sun.misc.Unsafe. It will still be possible to access existing internal APIs, but this will now require enumerating, as command-line parameters or JAR-file manifest attributes, each package on which encapsulation should be relaxed. The change will lead to more secure applications and less dependencies on non-standard internal implementations.

JEP 403 is the continuation of JEP 396 in JDK 16, which transitioned the JDK from a default of relaxed strong encapsulation to a default of strong encapsulation.

6. Deprecations and Removals

JEP 411: Deprecate the Security Manager for Removal

The Security Manager dates from Java 1.0. It has not been the primary means of securing client-side Java code for many years, and it has rarely been used to secure server-side code.

JEP 398: Deprecate the Applet API for Removal

The Applet API has become essentially irrelevant since all web-browser vendors have either removed support for Java browser plug-ins or announced plans to do so. The Applet API was previously deprecated (though not for removal) in Java 9 (JEP 289) in September 2017.

JEP 407: Remove RMI Activation

Remote Method Invocation (RMI) Activation mechanism has been removed.  This change does not affect the rest of RMI. The RMI Activation mechanism was deprecated for removal in JDK 15 in September 2020.

7. For OpenJDK Contributors

JEP 410: Remove the Experimental AOT and JIT Compiler

The experimental Java-based ahead-of-time (AOT) and just-in-time (JIT) compiler saw little use since its introduction in JDK 9, more widely supported alternatives have emerged, and the effort required to maintain them is significant.  As optional components, they were already removed from JDK 16. This JEP removes the source code from the OpenJDK project.
 

Tooling Support


Timely support for new features by tools and libraries helps drive developer productivity.  With Java 17, we continue to welcome the efforts of leading IDE vendors whose most timely updates offer developers support for current Java versions.  Developers can expect to take advantage of Java 17 support today with the following IDEs:

◉ JetBrains IDEA
◉ Eclipse via a separate marketplace solution

Source: oracle.com

Monday, August 22, 2022

Quiz yourself: Creating records within a Java sealed-type hierarchy

Oracle Java, Java Career, Java Skills, Java Jobs, Java Tutorial and Material, Java Career, Java Certification, Java Prep, Java Preparation

A record type is always implicitly final, so it cannot be extended by either a regular class or a record.

You’re designing an IoT device controlled by Java. The device has two modes, one for day and one for night. The modes differ in terms of configuration data, and that data should be constant, so you have decided to use Java records for the implementation. Further, since no other mode types are permitted, you have decided to seal the mode hierarchy something like this, but have not decided what the type of should be used to implement the parent of the sealed Mode hierarchy:

Read More: 1Z0-829: Oracle Java SE 17 Developer

public sealed <type> Mode permits DayModeRecord, NightModeRecord {

}

Which statement is true? Choose one.

A. The Mode type must be a class.

B. The Mode type must be a record.

C. The Mode type must be an interface.

D. The Mode may be either a class or an interface.

Answer. Generally, a sealed-type hierarchy can have a class or an interface as its root. The remainder of the hierarchy can contain classes or interfaces, provided all leaf nodes of the hierarchy are either final concrete classes or are non-sealed.

If a leaf element is non-sealed, it can be either a class or an interface.

However, a record is prohibited from using an extends clause, because all record types have java.lang.Record as their parent, and this cannot be made explicit. Consequently, a record cannot inherit from any user-selected class. Therefore, making Mode a class would prevent the two mode records from inheriting from the base. From this, you know that the Mode type must not be a class; therefore, option A and option D are incorrect.

Option B suggests that the Mode type should be a record. However, a record type is always implicitly final, so it cannot be extended by either a regular class or a record. Because of this, option B must be incorrect.

You’ve seen that an interface is permitted for the root (and potentially some further elements) in a sealed-type hierarchy, and although a record is prohibited from explicitly extending anything, records are permitted to implement interfaces. Option C proposes making the Mode type an interface, and it’s clearly not only a valid approach, but it’s the only valid way to create a sealed-type hierarchy where a leaf node in the sealed hierarchy is a record. From this, you can see that option C is correct.

Conclusion. The correct answer is option C.

Source: oracle.com