Monday, September 24, 2018

Java 11 released

[News] 
Java 11 is about to get released. Oh yes!
In this article we'll take a look what has been the addition in this version and what is about to die in subsquent releases. 

When is java 11 getting released?

Java 11 is going to be release on 25th Sep 2018 [source Wikipedia]. The release of java 9 is seen as a revolution with project Gigsaw, which brings us a modular structure of java libraries.
 With this release java provided us maintainability for larger java applications. On the other hand it becomes easy to use it with smaller applications as well. This improves application's security and maintainability with a sharp gain in their performance.
This module system is so powerful that it can modularize the jdk and other large scale legacy applications running on java. 
 In java 9 a new tool has been introduced JLink. This tool can assemble and optimize different modules and dependencies into a custom run-time image. There are other important features introduced with Java 9 but let's keep that for a different post.

What java 11 for the developers?

 So let’s now see what java 11 is about to bring for all of us.
 Following are the main features of java 11 as mentioned on openjdk :

 The most feature are new to me and difficult to cover this in post alone but this release catches my eyes because of its new Unicode 10 support. In Unicode 10 release we got some important symbol additions like Bitcoin sign.
There are some major deprecation coming with java 11 like Nashron JavaScript engine. The main reason behind deprecating Java Nashron engine is to frequent changes in ECMA script.

When it was released, it was a complete implementation of the ECMAScript-262 5.1 standard.With the rapid pace at which ECMAScript language constructs, along with APIs, are adapted and modified, we have found Nashorn challenging to maintain.

Second on the list is the Pack200 Tools and API, which is used for compressing jars and the JDK. Maintaining it is difficult, and with new compression schemes introduced in Java 9, there’s not much need for it anymore.

Thursday, September 20, 2018

Java Class Loader with example


I have been working with Java for many years now. The major black spot (from a developer's point of view) I see for any java application is Class Loading Internals. I always wonder how jdk and jvm works together to provide an environment for an application to run. What works behind the scene to provide all the resource that our small written code works? I will try to answer some of question in this article.

In below article I am going to explain in below sequence

·         What is a class loader
·         What is the difference between a class and Data
·         How class loader works
·         Java Class loader types
·         Custom Class Loader
·         Conclusion

What is a class loader?

A class loader is part of java runtime environment that dynamically loads java classes into java virtual machine.
The class loader is responsible for locating libraries, reading their contents, and loading the classes contained within the libraries.

 This loading is typically done "on demand", in that it does not occur until the class is called by the program. A class with a given name can only be loaded once by a given class loader.

In other words they are responsible to feed your java program with all dependent jars/classes required to execute your program as and when needed.

Also, these Java classes aren’t loaded into memory all at once, but when required by an application. This is where class loaders come into the picture. They are responsible for loading classes into memory.

What is the difference between a class and Data?

class represents the code to be executed, whereas data represents the state associated with that code. State can change; code generally does not. 
When we associate a particular state to a class, we have an instance of that class. So different instances of the same class can have different state, but all refer to the same code. 

In Java, a class will usually have its code contained in a .class file, though there are exceptions. 

Nevertheless, in the Java runtime, each and every class will have its code also available in the form of a first-class Java object, which is an instance of java.lang.Class. Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public, we can access it using dotted notation, like this:
java.lang.Class klass = Myclass.class;

Once a class is loaded into a JVM, the same class will not be loaded again.*

How java class loading works!

In this section first we understand the type of class loader available in java, their primary source to load classes and major responsibilities and in later section we will see how they actually works.

In Java each and every class is loaded by an instance of java.lang.ClassLoader. Developer can create their own class loaders by extending this class. We will see this in detail in last section.

The story starts when we run any java application(jvm started by typing java MyMainClass), the bootstrap class loader is responsible for loading key java classes like java.lang.Object  and other runtime code into memory(mainly from rt.jar) The runtime classes are packaged inside a jar present under JRE\lib\rt,jar. 

Now since you have all the bare minimum or essential classes to run java program, its time to load the classes required for the specific program that we are trying to run.

So next comes the java extension class loader. We can store extension libraries, those provide features that go beyond the code runtime code. This class loader is responsible for loading all .jar files present under java.ext.dirs path.

And the last but most important class loader from a developer’s point of view is the Appclassloader. The application class loader is responsible for loading all of the classes kept in the path corresponding to the java.class.path system property.

Now let’s understand how class loader works?

All class loaders except bootstrap class loader have a parent class loader. Moreover all the class loaders themselves a subclass of java.lang.Classloader. The most important aspect is to correctly set the parent class loader. The parent class loader for any class loader is the class loader instance that loader that class loader (point to be noted that a class loader is itself a class). 
A class is requested out of a class loader using the loadClass() method. Following is the code snippet if this method:

protected synchronized Class<?> loadClass


(String name, boolean resolve) throws ClassNotFoundException {
// First check if the class is already loaded
Class c = findLoadedClass(name);
if (== null) {
try {
if (parent != null) {
= parent.loadClass(name, false);
} else {
= findBootstrapClass0(name);
}
} catch (ClassNotFoundException e) {
// If still not found, then invoke
// findClass to find the class.
= findClass(name);
}
}
if (resolve) {
resolveClass(c);
}
return c;
}


To set the parent class loader, we have two ways to do so in the ClassLoader constructor. Let’s see them in below java class loader example.


public class MyClassLoader extends ClassLoader{

public MyClassLoader(){ 
  
       super(MyClassLoader.class.getClassLoader());
    }
}
public class MyClassLoader extends ClassLoader{
  public MyClassLoader(){
    super(getClass().getClassLoader());
  }
}

  

There are three important features of class loaders.
Delegation Model
Class loaders follow the delegation model where on request to find a class or resource, a ClassLoader instance will delegate the search of the class or resource to the parent class loader.
Let’s say we have a request to load an application class into the JVM. The system class loader first delegates the loading of that class to its parent extension class loader which in turn delegates it to the bootstrap class loader.
Only if the bootstrap and then the extension class loader is unsuccessful in loading the class, the system class loader tries to load the class itself.
Unique Classes

As a consequence of the delegation model, it’s easy to ensure unique classes as we always try to delegate upwards.
If the parent class loader isn’t able to find the class, only then the current instance would attempt to do so itself.
Visibility
In addition, children class loaders are visible to classes loaded by its parent class loaders.
For instance, classes loaded by the system class loader have visibility into classes loaded by the extension and Bootstrap class loaders but not vice-versa.
To illustrate this, if Class A is loaded by an application class loader and class B is loaded by the extensions class loader, then both A and B classes are visible as far as other classes loaded by Application class loader are concerned.
Class B, nonetheless, is the only class visible as far as other classes loaded by the extension class loader are concerned.

The Java language specification [8] gives a detailed explanation on the process of loadinglinking, and the initialization of classes and interfaces in the Java Execution Engine.


What all class loader present in Java

In first step lets first see how different classes are getting loaded by different class loaders using a simple example:

public void printClassLoaders() throws ClassNotFoundException {
      System.out.println("Classloader of this class:" + PrintClassLoader.class.getClassLoader());
   System.out.println("Classloader of Logging:" + Logging.class.getClassLoader());    
 System.out.println("Classloader of ArrayList:" + ArrayList.class.getClassLoader());
}

Output:

Class loader of this class:sun.misc.Launcher$AppClassLoader@18b4aac2

Class loader of Logging:sun.misc.Launcher$ExtClassLoader@3caeaf62
Class loader of ArrayList:null


As we can see, there are three different class loaders here; application, extension, and bootstrap (displayed as null).

The application class loader loads the class where the example method is contained. An application or system class loader loads our own files in the classpath.

Next, the extension one loads the Logging class. Extension class loaders load classes that are an extension of the standard core Java classes.

Finally, the bootstrap one loads the ArrayList class. A bootstrap or primordial class loader is the parent of all the others.

However, we can see that the last out, for the ArrayList it displays null in the output. This is because the bootstrap class loader is written in native code, not Java – so it doesn’t show up as a Java class. Due to this reason, the behavior of the bootstrap class loader will differ across JVMs.

Let’s now discuss more in detail about each of these class loaders.

 Bootstrap Class Loader

Java classes are loaded by an instance of java.lang.ClassLoader. However, class loaders are classes themselves. Hence, the question is, who loads the java.lang.ClassLoader itself?
This is where the bootstrap or primordial class loader comes into the picture.
It’s mainly responsible for loading JDK internal classes, typically rt.jar and other core libraries located in $JAVA_HOME/jre/lib directory. Additionally, Bootstrap class loader serves as a parent of all the other ClassLoaderinstances.
This bootstrap class loader is part of the core JVM and is written in native code as pointed out in the above example. Different platforms might have different implementations of this particular class loader.

Extension Class Loader

The extension class loader is a child of the bootstrap class loader and takes care of loading the extensions of the standard core Java classes so that it’s available to all applications running on the platform.
Extension class loader loads from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory or any other directory mentioned in the java.ext.dirs system property.

System Class Loader

The system or application class loader, on the other hand, takes care of loading all the application level classes into the JVM. It loads files found in the classpath environment variable, -classpath or -cp command line option. Also, it’s a child of Extensions classloader.

Custom Class Loaders


In this section let’s understand how to create a custom loader? 
Custom class loaders are really useful in case a java program needs to load some external/third party code in your java program that cannot be included in your java program directly or cannot be added in classpath. 
Let’s take an example of loading some classes from a FTP server:

public class CustomClassLoader extends ClassLoader {

 public CustomClassLoader(ClassLoader parent) {
  super(parent);
 }

 public Class getClass(String name) throws ClassNotFoundException {
  byte[] b = loadClassFromFTP(name);
  return defineClass(name, b, 0, b.length);
 }

@Override
public Class loadClass(String name) throws ClassNotFoundException {
  if (name.startsWith("in.thinkwithjava")) {
   System.out.println("Loading Class from Custom Class Loader");
   return getClass(name);
  }
  return super.loadClass(name);
 }

 private byte[] loadClassFromFTP(String fileName) { // Returns a byte array from specified file.   
  }
}

In above example, we defined a custom class loader that extends default class loader and load class from in.thinkwithjava package.
We set the parent class loader in the constructor. Then we load the class using FTP specifying a fully qualified class name as an input

Now let’s understand some essential methods of java.lang.Classloader in order to understand the working properly.
 The loadClass() Method

public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {

This method is responsible for loading the class given a name parameter. The name parameter refers to the fully qualified class name.
This method serves as an entry point for the class loader.

The default implementation of the method searches for classes in the following order:
1.    Invokes the findLoadedClass(String) method to see if the class is already loaded.
2.    Invokes the loadClass(String) method on the parent class loader.
3.    Invoke the findClass(String) method to find the class.
The defineClass() Method

protected final Class defineClass(String name, byte[] b, int off, int len) 

throws ClassFormatError


This method is responsible for the conversion of an array of bytes into an instance of a class. And before we use the class, we need to resolve it.
In case data didn’t contain a valid class, it throws a ClassFormatError.
Also, we can’t override this method since it’s marked as final.
The findClass() Method

protected Class findClass(

String name) throws ClassNotFoundException
  

This method finds the class with the fully qualified name as a parameter. We need to override this method in custom class loader implementations that follow the delegation model for loading classes.
Also, loadClass() invokes this method if the parent class loader couldn’t find the requested class.
The default implementation throws a ClassNotFoundException if no parent of the class loader finds the class.
The getParent() Method

public final ClassLoader getParent()


This method returns the parent class loader for delegation.

The getResource() Method

public URL getResource(String name)



This method tries to find a resource with the given name. It will first delegate to the parent class loader for the resource. If the parent is null, the path of the class loader built into the virtual machine is searched.
If that fails, then the method will invoke findResource(String) to find the resource. The resource name specified as an input can be relative or absolute to the class path.

It returns an URL object for reading the resource, or null if the resource could not be found or if the invoker doesn’t have adequate privileges to return the resource. It’s important to note that Java loads resources from the classpath.

Finally, resource loading in Java is considered location-independent as it doesn’t matter where the code is running as long as the environment is set to find the resources.
In last section we had a brief explanation of how to create a custom one with example and seen the various methods. 

Conclusion

Class loader are essential and key feature for java programs. We’ve provided a good introduction as part of this article.

We talked about different types of class loaders namely – Bootstrap, Extensions and System class loaders. Bootstrap serves as a parent for all of them and is responsible for loading the JDK internal classes. Extensions and system, on the other hand, loads classes from the Java extensions directory and class path respectively.
Then we talked about how class loaders work and we discussed some features such as delegation, visibility, and uniqueness.

Thanks for reading!


Wednesday, August 22, 2018

Coding practice and conventions in Java

Anyone can write code a computer can understand, but professional developers write code *humans* can understand. Clean code is a reader-focused development style that produces software that's easy to write, read and maintain.



I have seen code written for the products which are serving more than 2 dozen clients with single database and 1 codebase. This is amazing. The reason they were successfully managed to do so was because of the coding standards they follow. The use of standard coding practice in your project makes life easy. 

If you set your standards very much in the beginning before you actually start coding for a product, it will become the rule for the fellow developers and makes life earsier for the new comers and the coders who have to decode you wrote in the beginning.

Having standards gives you the checkpoints to identify if a developer writing a quality code or not. 

https://amzn.to/2wKFA4y


Also code conventions are important to programmers for a number of reasons:


  • 80% of the lifetime cost of a piece of software goes to maintenance.
  • Hardly any software is maintained for its whole life by the original author.
  • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
  • If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create

I will try to cover all possible and important part of java standards in following sections.

 Java Source files

    Beginning comments

    All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice:

    /*
     * Classname
     * 
     * Version information
     *
     * Date
     * 
     */
     * Copyright notice
    

    Package and Import statements

    The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example:

    package java.awt;

    import java.awt.peer.CanvasPeer;

    Indentation

    Line length

    Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools.

    Wrapping Lines

    When an expression will not fit on a single line, break it according to these general principles:
    1. Break after a comma.
    2. Break before an operator.
    3. Prefer higher-level breaks to lower-level breaks.
    4. Align the new line with the beginning of the expression at the same level on the previous line.
    5. If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.

    Examples:

    Here are some examples of breaking method calls:


    someMethod(longExpression1, longExpression2, longExpression3,
            longExpression4, longExpression5);

    var = someMethod1(longExpression1,
                    someMethod2(longExpression2,
                            longExpression3));


    Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.

    longName1 = longName2 * (longName3 + longName4 - longName5)
               + 4 * longname6; // PREFER

    longName1 = longName2 * (longName3 + longName4
                           - longName5) + 4 * longname6; // AVOID 

    Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.

    //CONVENTIONAL INDENTATION
    someMethod(int anArg, Object anotherArg, String yetAnotherArg,
               Object andStillAnother) {
        ...
    }

    //INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
    private static synchronized horkingLongMethodName(int anArg,
            Object anotherArg, String yetAnotherArg,
            Object andStillAnother) {
        ...
    }

    Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:

    //DON'T USE THIS INDENTATION
    if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) { //BAD WRAPS
        doSomethingAboutIt();            //MAKE THIS LINE EASY TO MISS

    //USE THIS INDENTATION INSTEAD
    if ((condition1 && condition2)
            || (condition3 && condition4)
            ||!(condition5 && condition6)) {
        doSomethingAboutIt();

    //OR USE THIS
    if ((condition1 && condition2) || (condition3 && condition4)
            ||!(condition5 && condition6)) {
        doSomethingAboutIt();
    }

    Here are three acceptable ways to format ternary expressions:

    alpha = (aLongBooleanExpression) ? beta : gamma;  

    alpha = (aLongBooleanExpression) ? beta
                                     : gamma;  

    alpha = (aLongBooleanExpression)
            ? beta 
            : gamma;

    Declarations

    Number Per Line

    One declaration per line is recommended since it encourages commenting. In other words,

      int level; // indentation level
      int size;  // size of table

    is preferred over

      int level, size;

    Do not put different types on the same line. Example:

      int foo,  fooarray[]; //WRONG!   

    The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs

    Initialization


    Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

    Placement

    Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

    Class and Interface Declarations

    When coding Java classes and interfaces, the following formatting rules should be followed:

    No space between a method name and the parenthesis "(" starting its parameter list
    Open brace "{" appears at the end of the same line as the declaration statement
    Closing brace "}" starts a line by itself indented to match its corresponding opening statement, except when it is a null statement the "}" should appear immediately after the "{"

    class Sample extends Object {
        int ivar1;
        int ivar2;

        Sample(int i, int j) {
            ivar1 = i;
            ivar2 = j;
        }

        int emptyMethod() {}

        ...
    }


    Methods are separated by a blank line


    Happy reading...

    Java garbage collection

    In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...