ஓம் பூர் புவஸ்ஸூவ
தத் சவிதுர்வரேண்யம்
பர்கோ தேவஸ்ய தீமஹி
தியோ யோ ந: ப்ரசோதயாத்|

காயத்திரி’ என்னும் ஒலியின் அளவைக் கொண்டு இந்த மந்திரம் இயற்றப்பட்டதால் “காயத்திரி மந்திரம்”.நமது புத்தியை இயங்கச் செய்யும் பரமாத்மாவை நாம் வணங்குவோம் என்பது சுருக்கமான பொருள்.சூரியனுடைய ஒளியை தியானிக்கின்றோம் என்பதால் கண்களை மூடிய நிலையில் சூரிய ஒளியில் நின்று இதைச் சொல்ல வேண்டும் என்பது யதார்த்தமான விஷயம்

Om Bhuur-Bhuvah Svah
Tat-Savitur-Varennyam |
Bhargo Devasya Dhiimahi
Dhiyo Yo Nah Pracodayaat ||

Full long version

Om bhUH, Om bhuvaH, Om svaH, Om mahaH, Om janaH, Om tapaH, Om satyam
Om tat savitur varenyaM, bhargo, devasya dhImahi, dhIyo yo naH, prachodayAt
Om Apo jyotiH rasoamRitaM brahma, bhur bhuvas svar Om.

A Japanese soap factory had a problem: they sometimes shipped empty boxes, without the soap inside. This was due to the way the production line was set up, and people with experience in designing production lines will tell you how difficult it is to have everything happen with timings so precise that every single unit coming out of it is perfect 100% of the time. Customers who come all the way to the supermarket would end up buying someone else’s product.

Understanding how important that was, the CEO of the soap factory got the top people in the company together and they decided to start a new project, in which they would hire an external engineering company to solve their empty boxes problem, as their engineering department was already too stretched to take on any extra effort.

The project followed the usual process: budget and project sponsor allocated, RFP, third-parties selected, and six months (and $8 million) later they had a fantastic solution — on time, on budget, high quality and everyone in the project had a great time. They solved the problem by using some high-tech precision scales that would sound a bell and flash lights whenever a soap box weighing less than it should. The line would stop, and someone had to walk over and yank the defective box out of it, pressing another button when done.

A while later, the CEO decides to have a look at the ROI of the project: amazing results! No empty boxes ever shipped out of the factory after the scales were put in place. Very few customer complaints, and they were gaining market share. “That’s some money well spent!” – he says, before looking closely at the other statistics in the report. It turns out, the number of defects picked up by the new high precision scales was “zero” after three weeks of production use. It should’ve been picking up at least a dozen a day, so maybe there was something wrong with the report. He filed a bug against it, and after some investigation, the engineers come back saying the report was actually correct. The scales really weren’t picking up any defects, because all boxes that got to that point in the conveyor belt were good.

Puzzled, the CEO travels down to the factory, and walks up to the part of the line where the high precision scales were installed. A few feet before it, there was a $ 20 desk fan, blowing the empty boxes out of the belt and into a bin.

“Oh, that — one of the guys put it there ’cause he was tired of walking over every time the bell rang”, says one of the workers.
Moral of the Story: Everyone has a “solution” sometimes requiring an expenditure of “8 million bucks”. It requires an engineer with a high spirit of innovation and ingenuity to come up with a “$ 20 – simple cost-effective solution”!

Below is a code example of CustomClass Loader which Servers use internally for HotCode Swap without restarting the server.When you change the Quote in ServerImpl.java file the file should be reloaded by selecting the RELOAD option while running Client.java

IServer.java

public interface IServer {
	public String getQuote();
}

ServerImpl.java

public class ServerImpl implements IServer{
	@Override
    public String getQuote() {
        return "Its Working Man";
    }
}

Client.java

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Client {
    static ClassLoader cl;
    static IServer server;

    public static void reloadServer() throws Exception {
        URL[] urls = new URL[]{new URL("file:///D:/java/HotDeplyment/appclasses")};
        System.out.println("Reloaded.....");
        cl = new URLClassLoader(urls);
        server  = (IServer) cl.loadClass("com.mugil.org.ServerImpl").newInstance();
    }

    public static void main(String [] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        reloadServer();
        while (true) {
            System.out.print("Enter QUOTE, RELOAD, or QUIT: ");
            String cmdRead = br.readLine();
            String cmd = cmdRead.toUpperCase();
            if (cmd.equals("QUIT")) {
                return;
            } else if (cmd.equals("QUOTE")) {
                System.out.println( server.getQuote());
            } else if (cmd.equals("RELOAD")) {
            	reloadServer();
            }
        }
    }
}

The Above code is not working as windows is not clearing cached .class files or JAR files. So the alternative is to try with the below Custom Class Loader(MyURLClassLoader) which in turn extends URLClassLoader again.

MyURLClassLoader.java

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.jar.JarFile;

public class MyURLClassLoader extends URLClassLoader {

	public MyURLClassLoader(URL[] urls, ClassLoader parent) {
	    super(urls, parent);
	}

    /**
     * Closes all open jar files
     */
    public void close() {
        try {
            Class clazz = java.net.URLClassLoader.class;
            Field ucp = clazz.getDeclaredField("ucp");
            ucp.setAccessible(true);
            Object sunMiscURLClassPath = ucp.get(this);
            Field loaders = sunMiscURLClassPath.getClass().getDeclaredField("loaders");
            loaders.setAccessible(true);
            Object collection = loaders.get(sunMiscURLClassPath);
            for (Object sunMiscURLClassPathJarLoader : ((Collection) collection).toArray()) {
                try {
                    Field loader = sunMiscURLClassPathJarLoader.getClass().getDeclaredField("jar");
                    loader.setAccessible(true);
                    Object jarFile = loader.get(sunMiscURLClassPathJarLoader);
                    ((JarFile) jarFile).close();
                } catch (Throwable t) {
                    // if we got this far, this is probably not a JAR loader so skip it
                }
            }
        } catch (Throwable t) {
            // probably not a SUN VM
        }
        return;
    }
}

In the below code the CustomClass Loader is called to load the classes which inturn calls the Super Class loader which is again Loaders from URL Class Loader.Once it is done we have defined a custom close method which closes the JAR files or .class files which is loaded by class loader.

TestClassLoader.java

package com.mugil.org;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;

public class TestClassLoader {
	static ClassLoader cl;
    static IServer server;
	
	public static void main(String[] args) throws Exception {
		
		while(true) {
			try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			TestClassLoader obj = new TestClassLoader();
			obj.loadAndInstantiate();			
			System.out.println(server.getQuote());			
			}
			catch (Exception e){
				
			}
			finally {
				try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
			}
		}    
	}
	
	void loadAndInstantiate() throws Exception {
	    MyURLClassLoader cl = null;
	    try {	    	
	        File file = new File("D:\\java\\HotDeplyment\\bin\\Sample.jar");
	        String classToLoad = "com.mugil.org.ServerImpl";
	        URL jarUrl = new URL("file:" + file.getAbsolutePath());
	        cl = new MyURLClassLoader(new URL[] {jarUrl}, getClass().getClassLoader());
	        Class loadedClass = cl.loadClass(classToLoad);
	        Object o = loadedClass.getConstructor().newInstance();
	        server  = (IServer) o;
	        
	    } finally {
	        if(cl != null)
	            cl.close();
	    } 
	}
}

Since the infinite while loop is called indefinitely with the thread sleep interval of every 3 seconds we replace the JAR file in the middle which takes the class from the new JAR file loaded.You need to change the ServerImpl.java file and build the JDK before you want to see the changes

Output

.
.
Its Working Man
Its Working Man
Its Working Man
Its Working Man
Its Working 
Its Working 
Its Working 
.
.

The Above code is not working either

Why Tomcat Server does not needs restart if changes are done in servlet and JSP?
Tomcat is capable of adding/modifying classpath to Web Application classloader at runtime. Tomcat will be having their custom Classloader implementation which allows them to add the classpaths at runtime.a new classloader is created for the Servlet/JSP with Application classloader as parent classloader. And the new classloader will load the modified class again.

It is always best to reload the entire application incase changes are done to servlet. If you were simply to reload one class, in isolation, you might break dependencies or miss some initialization steps. Therefore, it’s much safer to reload the entire application clicking deploy option in tomcat server.JSPs on the other hand, when properly coded, shouldn’t have anything in them by markup text. So reloading a single JSP, without reloading the entire app, should be safe. By default, tomcat is started in development mode, which means JSP-derived servlets recompiled when a change is detected.

In the web.xml you need to set the below config

<servlet>
   .
   .
    <!-- Add the following init-param -->
    <init-param>
        <param-name>development</param-name>
        <param-value>true</param-value>
    </init-param>
   .
   .
   .
</servlet>

In the Server.xml reloadable should be set to true

<Context path="/simple" docBase="webapps/simple"  debug="0" reloadable="true" ></Context>

More on how CustomClass loader works for Hot Deployment here

How it Works

  1. We have JSON file with Location and Name of Factory Class
  2. Using Configuration.java we read the JSON File and read the Configuration
  3. We run TasteFoodFromMenu.java by supplying the JSON file Location as Input
  4. Now by the above method the JAR’s could be built independently and by changing the JSON file we could make changes and deploy the code without restarting the Server

For more detail refer here

Configuration.java

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Configuration {

    public static Configuration loadConfiguration(String fileName) throws IOException {    	
    	//Read Name of File
        Path path = FileSystems.getDefault().getPath(fileName);
        
        //Read Contents of File
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        
        ObjectMapper mapper = new ObjectMapper();
        
        //Map Location and FactoryType
        Configuration config = mapper.readValue(contents, Configuration.class);
        return config;
    }

    private String factoryType;
    private String location;


    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getFactoryType() {
        return factoryType;
    }

    public void setFactoryType(String factoryType) {
        this.factoryType = factoryType;
    }
}

TasteFoodFromMenu.java

public class TasteFoodFromMenu {
	  public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
	        Configuration configuration = Configuration.loadConfiguration(args[0]);
	        String location = configuration.getLocation();
	        URL url = new URL(location);
	        URLClassLoader ucl = new URLClassLoader(new URL[]{url});
	        Class<IFoodFactory> cls = (Class<IFoodFactory>) Class.forName(configuration.getFactoryType(), true, ucl);
	        IFoodFactory cameraFactory = cls.newInstance();
	        IFood camera = cameraFactory.prepareFood(); 
	        camera.serveFood();
	    }
}

config.json

{
  "factoryType": "com.mugil.food.ChineseFoodFactory",
  "location": "file:///D:/java/ReadConfFromJSON/lib/FoodMenu.jar"
}

Abstract Factory Pattern
The Abstract Factory Pattern consists of an AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct and Client. We code against AbstractFactory and AbstractProduct and let the implementation to others to define ConcreteFactory and ConcreteProduct

IFoodFactory.java(AbstractFactory)

public interface IFoodFactory {
	public IFood prepareFood();
}

IFood.java(AbstractProduct)

public interface IFood {
	public void serveFood();
}

ItalianFoodFactory.java(ConcreteFactory)

public class ItalianFoodFactory implements IFoodFactory{
	@Override
	public IFood prepareFood() {
		return new ItalianFood();
	}
}

ChineseFoodFactory.java(ConcreteFactory)

public class ChineseFoodFactory implements IFoodFactory{
	@Override
	public IFood prepareFood() {
		return new ChineseFood();
	}
}

ItalianFood.java(ConcreteProduct )

public class ItalianFood implements IFood{
	@Override
	public void serveFood() {
	  System.out.println("Pepperoni Pizza by Sam");		
	}
}

ChineseFood.java(ConcreteProduct )

public class ChineseFood implements IFood{
	@Override
	public void serveFood() {
		System.out.println("Snake Soup by Bruce");;
	}		
}

TasteFood.java(Client)

public class TasteFood {
	public static void main(String[] args) {
		IFoodFactory objFoodFactory = new ChineseFoodFactory();
		IFood objFood = objFoodFactory.prepareFood();		
		objFood.serveFood();
	}
}

Output

Snake Soup by Bruce

With the Factory pattern, you produce instances of implementations (ChineseFood, ItalianFood, ThaiFood, etc.) of a particular interface — say, IFood.
With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFoodFactory or an IJuiceFactory, without requiring your warehouse to know anything about Food or Juices.Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

Factory Pattern Abstract Factory pattern
Factory Method creates objects through inheritance Abstract Factory creates objects through composition
Factory Method pattern is responsible for creating products that belong to one family Abstract Factory pattern deals with multiple families of products i.e. Food, Juice, Dessert
Factory Method uses interfaces and abstract classes to decouple the client from the generator class and the resulting products Abstract Factory has a generator that is a container for several factory methods, along with interfaces decoupling the client from the generator and the products

Download example of Abstract Factory pattern from here

Class Loaders
Let’s take two simple Java Files as below

Helper.java

package com.mugil.org;
public class Helper {
	public String getMessage()
	{
		return "Helper Method";
	}
}

TestHelper.java

package com.mugil.org;
public class TestHelper {
	public static void main(String[] args) {
		Helper objHelper = new Helper();
		System.out.println(objHelper.getMessage());
	}
}

How to Compile class in Command Prompt
Normally when you compile Java class the class files would be created in bin folder with
the folder structure same as package name bin->com->mugil->org.
When you want the .class to be created in a specific folder then use the below command

D:\java\ClassLoaders>javac -d classes -sourcepath src src\com\mugil\org\Helper.java

Classes folder should be created manually or it’s going to throw
javac: directory not found: classes

Before Running the code the Classpath needs to be set which could be done either globally
by adding to the System classPath or locally at the application level

To Set globally the following should be run in Command Prompt

D:\java\ClassLoaders>set CLASSPATH=classes

After this, the Java code can be run as below

D:\java\ClassLoaders>java com.mugil.org.TestHelper
Helper Method

Setting Globally is not a good idea as other applications Classpath would be affected.If you
have set classpath globally chances are you may end up running wrong JAR file in the Classpath
The Better option is to set classpath while running the application itself

D:\java\ClassLoaders>java -cp classes com.mugil.org.TestHelper
Helper Method

Now let’s see how to take .class files in some other folder or .class files in JAR folder to

To run the .class file in other folders along with the one we are running adding the .class files separated by semicolon would be an easy way
as below

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper
Helper Method

The Helper.class is moved to D:\class1 folder and TestHelper.class is in D:\java\ClassLoaders\classes folder
TestHelper.class needs Helper.class to run.

Now how about JAR Files

D:\class1>jar cvf helper.jar com\mugil\org\Helper.class
added manifest
adding: com/mugil/org/Helper.class(in = 296) (out= 227)(deflated 23%)

To run the classes in the JAR Files the same command applies.D:\class1 is the location where the JAR’s are located(helper.jar).

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper
Helper Method

Once the JAR is created the .class files can be deleted and added to lib folder

While Creating JAR make sure you maintain the folder structure.Creating JAR file without adding com\mugil\org folder will result in classNotFound Exception

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes\lib\Helper.jar;D:\java\ClassLoaders\classes\; com.mugil.org.TestHelper

Class loaders are the part of the Java Runtime Environment that dynamically loads Java classes into the Java virtual machine. It is responsible for locating libraries, reading content and loading the classes contained within the libraries. When JVM is started three class loaders are used

How ClassLoaders works

  1. When JVM requests for a class, it invokes loadClass function of the ClassLoader by passing the fully classified name of the Class.
  2. loadClass function calls for findLoadedClass() method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times.
  3. If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class.
  4. If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.

1. Bootstrap class loader (Written in C)
2. Extensions class loader (Written in Java)
3. System or Application class loader (Written in Java)

Apart from CLASSPATH java looks into two other locations to load the JAR Folder
C:\Program Files\Java\jdk1.8.0_111\jre\lib in JRE installation Folder
C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext

Bootstrap class loader
It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes

rt.jar is one of the JAR files in JRE Folder. You can see the content in rt.jar by renaming it into rt.jar.
rt.jar is loaded by the bootstrap class loader.

Extensions class loader
It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
You can add your JAR files like DB Connection JAR in the EXT folder and would be available to all application which runs on JVM

helper.jar added to ext folder

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes;D:\class1; com.mugil.org.TestHelper
Helper Method

D:\java\ClassLoaders>java -cp D:\java\ClassLoaders\classes; com.mugil.org.TestHelper
Helper Method

Note:In the second statement the D:\class1 is missing which has the JAR files which is now moved to EXT folder.No need to specify the JAR files as JAR files in EXT are loaded by default

System (or) Application class loader
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.

Delegation of Classes

  1. Delegation Classes are classes which delegates the call to its Parent Class which inturn Delegates to its Parent
  2. Each class loader has a parent. Class Loaders may delegate to its Parent. Parent may or may not load the class
  3. Loaded classes are always cached
  4. Application loader asks the Extension Class loader which inturn asks Bootstap loader
  5. If Bootstap loader couldnt find the class it will send fail message which makes the Extension Class loader to search for classes within
  6. If Extension loader couldnt find the class it will send fail message to Application Class Loader and makes to search for classes within
  7. If Application Class loader couldnt find the class NoClassDefinition Error would be Displayed

import java.net.URLClassLoader;

public class Delegation 
{
	public static void main(String[] args) 
	{
		URLClassLoader classloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
		
		do {
			System.out.println(classloader);
		} while ((classloader = (URLClassLoader)classloader.getParent()) != null);
		
		System.out.println("Bootstrap ClassLoader");
	}
}

Output

sun.misc.Launcher$AppClassLoader@1497b7b1
sun.misc.Launcher$ExtClassLoader@749cd006
Bootstrap ClassLoader

To See the location of the Class Files loaded you can use the below code

.
.
do {
			System.out.println(classloader);
			
			for(URL url : classloader.getURLs())		
			 System.out.println("\t %s"+ url.getPath());
			
		} while ((classloader = (URLClassLoader)classloader.getParent()) != null);
.
.

Output

sun.misc.Launcher$AppClassLoader@1497b7b1
	 %s/D:/java/ClassLoaders/bin/
sun.misc.Launcher$ExtClassLoader@749cd006
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/access-bridge-64.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/dnsns.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/jaccess.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/localedata.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunec.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunjce_provider.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/sunmscapi.jar
	 %s/C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/zipfs.jar
Bootstrap ClassLoader

In the above Output, you can see the Application Class Loaders loads the Java class from the Project Directory and EXT jars from the EXT C:/Program%20Files/Java/jdk1.7.0_45/jre/lib/ext/ Folder

Why we need Custom ClassLoader?
Whenever a class is referenced in a java program it is loaded using JVM’s bootstrap class loader. This often becomes a problem when two different classes with same name and same package declaration are to be loaded. For example relying on JVM’s class loader one cannot load two different versions of the same JDBC driver. The work around to this problem is lies in making a custom class loader and loading classes directly from JAR archives.

Other Reasons

  1. Better Memory Management Unused modules can be removed which unloads the classes used by that module, which cleans up memory.
  2. Load classes from anywhere Classes can be loaded from anywhere, for ex, Database, Networks, or even define it on the fly.
  3. Runtime Reloading Modified Classes Allows you to reload a class or classes runtime by creating a child class loader to the actual class loader, which contains the modified classes.Hot Deployment
  4. Provides Modular architecture Allows to define multiple class loader allowing modular architecture.
  5. Support Versioning Supports different versions of class within same VM for different modules. Multiple Version Support
  6. Avoiding conflicts Clearly defines the scope of the class to within the class loader.
  7. Class loading mechanism forms the basis of Inversion of Control

Simple URL Class Loader
In the below example we are using URL Class Loading method to load the Classes from the JAR file.We can load Classes from File Based URL or Network Based URL
We can also load class from DB

SimpleClassLoader.java

public class SimpleClassLoader {
	public static void main(String[] args) {
		URL url;
        try {
            url = new URL("file:///D:/jars/helper.jar");
            URLClassLoader ucl = new URLClassLoader(new URL[]{url});
            Class clazz = ucl.loadClass("com.mugil.org.Helper");
            Object o = clazz.newInstance();
            Helper objHelper = (Helper)o;
            System.out.println(o.toString());
    		System.out.println(objHelper.getMessage());            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
	}
}

Output

Helper Method
com.mugil.org.Helper@4631c43f

Note: In the above example you can see the Typecasting from Object to Helper which again makes the code tightly coupled and defeats the purpose of the class loader dynamically loads Java classes into the Java Virtual Machine. To resolve this issue we can use Interface which is loaded by application class loader with the implementing class loaded by our own class loader.

Account.java

public interface Account {
	public Integer getInterestRate(); 
}

SavingsAccount.java

public class SavingsAccount implements Account {
	@Override
	public Integer getInterestRate() {
		return 10;
	}
}

Implementation classes added to our JAR so it can be loaded by our Class Loader

D:\java\ClassLoaders\bin> jar cvf Accounts.jar com\mugil\org\SavingsAccount.class
added manifest
adding: com/mugil/org/SavingsAccount.class(in = 496) (out= 301)(deflated 39%)

CalculateInterest.java

public class CalculateInterest {
	public static void main(String[] args) 
	{
		URL url;
        try {
            url = new URL("file:///D:/jars/Accounts.jar");
            URLClassLoader ucl = new URLClassLoader(new URL[]{url});
            Class clazz = ucl.loadClass("com.mugil.org.SavingsAccount");
            Account o = (Account)clazz.newInstance();            
            System.out.println(o.toString());
    		System.out.println(o.getInterestRate());            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
	}
}	

In the above code I can change the logic interest is calculated in the SavingsAccount and redeploy the JAR without taking effect in other parts of the program.

The above jar file could be loaded accross network by giving URL as below

.
.
URL url = new URL("http://localhost:8080/Accounts.jar");
.
.

Multiple version Support of Same JAR

Java bytecode is universal across platforms, you can use it to instrument classes on any system: a measure which methods are called, suppress security-critical calls, divert System.out accesses to your own custom logging routines, or perform advanced dynamic bug-testing routines.

	public static void main(String[] args) {
		try { 
            URL url1 = new URL("file:///D:/jars/Accounts1.jar"); 
            URLClassLoader ucl1 = new URLClassLoader(new URL[]{url1}); 
            Class clazz1 = Class.forName("com.mugil.org.SavingsAccount", true, ucl1);
            Account quote1 = (Account) clazz1.newInstance();

            URL url3 = new URL("file:///D:/jars/Accounts.jar");
            URLClassLoader ucl3 = new URLClassLoader(new URL[]{url3});
            Class clazz2 = Class.forName("com.mugil.org.SavingsAccount", true, ucl3);
            Account quote2 = (Account) clazz2.newInstance();

            System.out.printf("clazz1 == clazz2? %b\n", clazz1 == clazz2);
            System.out.printf("quote1.class == quote2.class? %b\n", quote1.getClass() == quote2.getClass());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
	}

Output

clazz1 == clazz2? false
quote1.class == quote2.class? false

Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method compareTo is used for comparison purpose
Functional Interface is an interface which has one and only one abstract method. Apart from abstract method it can have any number of default and static methods which have an implementation and are not abstract and overriden method from Object.These interfaces are also called Single Abstract Method Interfaces. Few Functional Interfaces are Comparable, Runnable and etc.

Example of Functional Interface

@FunctionalInterface
public interface MyFunctionalInterface 
{
	public void MethodOne(int i, double d);
} 
@FunctionalInterface
public interface MyFunctionalInterface 
{
	public void MethodOne(int i, double d);
	
	default boolean methodTwo(String value) 
	{
        return true;
  }
} 

@FunctionalInterface annotation is used to mark an interface as Functional Interface
not mandatory to use it. If the interface is annotated with @FunctionalInterface annotation and when we
try to have more than one abstract method, it throws compiler error.

One of the major benefits of functional interface is we can use lambda expressions to instantiate them.

For example in Java if we have to instantiate runnable interface anonymously, then our code looks like below. Its bulky

Runnable r = new Runnable(){
 @Override
 public void run() 
 {
	System.out.println("My Runnable");
 }};

lambda expressions for the above method implementation is

Runnable r1 = () -> {
 System.out.println("My Runnable");
};

Function interface with abstract method and default, static methods which have an implementation and are not abstract and methods overriden from Object Class.

@FunctionalInterface
public interface MyFunctionalInterface 
{
	public void oneMethod(int i, double d);
	public String toString();
	public boolean equals(Object o);

	public static int getSum(int a,int b)
        {// valid->method static
		return a+b;
	}

	public default int getMulty(int c,int d)
        {//valid->method default
		return c+d;
        }
}

Consonant
The word consonant is also used to refer to a letter of an alphabet that denotes a consonant sound. The 21 consonant letters in the English alphabet are B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, X, Z, and usually W and Y

Vowels
a,e,i,o,u, y is Special Vowel

Bicycle
Pretty
Why

In the above words y is spelled like i

Noun is person, place, animal, thing e.g. book,park,umbrella, elephant, dcotor, orange

Use of Articles in Front of Vowels
A Banana
An Apple(Apple starts with vowel A)
A Cat
A Boy
An Egg
The Cat(Particular Cat)

Singular & Plural Noun
Singular Noun
A ring
A Dog
A Teacher
An Apple
An Egg

Plural Noun and their Singular
Two Rings – A Ring
Three Dogs – A Dog
Four Teachers – A Teacher
Five Apples – An Apple
Six Eggs – An Egg

To make plural we use s (or) es
A Bus – Two Buses
A Box – Two Boxes
A Watch – Two Watches

How to Decide s or es
If the noun ends with ch,sh,x,ss we should put es
Church – Churches
Brush – Brushes
Fox – Foxes
Dress – Dresses

Special Noun for Noun
Potato – Potatoes
Tomato – Tomatoes
Volcano – Volcanoes

where as
Photo – Photos

Pronoun (or) Subjective Pronoun
I,He,She, It, You,We,They

Jenny Sings – She Sings
Jack Sings – He Sings
Jenny and Jack Sings – They Sings
The Cat Runs – It Runs
The Dog and Cat Runs – They Runs
My Students Study – They Study
John is Handsome – He is Handsome
Pizza is Delicious – It is Delicious

“Be” verbs indicate a state of being.
Am, is, are

Pronoun + Be VerbContractions
I am – I’m
He is – He’s
She is – She’s
It is – It’s
You are – You’re
We are – We’re
They are – They’re

A Contraction is common way to tell Subjective Pronoun and Be Verb

I’m a Student [Don’t miss a in middle]
It’s a Dog [Don’t miss a in middle]

We’re Students [Many Student so no a In between]
They’re Students [Many Student so no a In between]

Pronouns + Be Verb + Not
I’m not a Student
He’s not a Student
You’re not Students [Note : a is missing in front of Student]
They’re not Students [Note : a is missing in front of Student]

BE verbs comes in front of a question
Am I a teacher

BE verbs follows pronoun in answer
I am not a teacher

Question Singular and Plural
What is it?
It is a box

If there is single box it would be it

What are they?
They are boxes

If there are multiple boxes it would be they

Examples
What is it?
It is a cat.

What are they?
They are Cats

Singular – is – Only one thing
Plural – are – Group of thing

This and That
We use this to point to one noun that is close

I.E.
This is flower

We use that to point to one noun that is away

I.E.
That is flower

This and That in Question
Example
Is this a Flower?
Is that a Flower?

These and Those
These are Flowers(Closer)
Those are Flowers(Away)

These and Those in Questions
Are these Flowers?(Closer) No they aren’t.
Are those Flowers?(Away) No they aren’t.

Close Far
This That
These Those

Possessive Adjective
Used to tell something belongs to me or Someone else

Subjective Pronoun Possessive Adjective
I My
He His
She Her
It Its
You Your
We Our
They Their

Possessive Adjective
Its and It’s are different
Your and You’re are different
Their and They’re are different

Possessive Pronoun
Something belongs to us (or) something owned by us. Possessive pronoun and possessive adjectives are almost same. In possessive pronoun you don’t stretch much on noun.

Possessive Adjective Possessive Pronoun
This is his Hat This is his
This is her dress This is hers
This is their house This is theirs
This is their books These are theirs

A/An/The

a/an the
anyone thing specific thing
first time second time
article to be used in front of noun One and Only

Examples
A banana is Delicious [All banana is delicious]
The banana is Old[Particular banana is old]

I watched a movie [First Time]
I watched the Movie.[Second Time]

The Sun[One and Only]
The Moon[One and Only]

More Examples
A lion is Dangerous Animal[All lions are dangerous]
It’s a Dog[Talking first time]
The Dog is Cute[Talking Second Time]
It’s an ant[Starts with vowel]
The ant is small[Particular ant]
It’s the moon.The moon is round[One and only moon]

Prepositions
a word governing, and usually preceding, a noun or pronoun and expressing a relation to another word or element in the clause, as in ‘the man on the platform’, ‘she arrived after dinner’, ‘what did you do it for ?’.

In/On/Under
Prepositions to tell where something is

The cat is in the Box
The Cat is on the Chair
The Cat under the Chair

Adjectives
Tells the attribute of a noun, such as sweet, red, or technical.
Size, Shape, Color. Adjectives comes before noun

Examples
Its a Black Marker
Its a Blue Bird
Its an ugly ant
They are Red Apples

Have/Has
Both are used to show possessions
Have is used with some pronouns and plural nouns

I.E.
I have
You have
We have
They have

Examples
I have a great English teacher.
You have toothpaste on your chin.
We have a meeting at 12.
Nurses have a difficult job.

Has is used with the third person singular

I.E.
He has
She has
It has

Examples
She has a great personality.
He has a new haircut.
The washing machine has a leak in it.
It has a hole near the door.

Sentence Replaced with Subjective pronoun
The girl has long hair She has long hair
The Boys have caps They have caps
My mother and I have a Car We have a car

I have a Friend
He has an Umbrella
The dog has a bone
It has a bone

In negative sentence we use always have not has.The only thing which needed to be taken care is doesn’t or dont

  1. I don’t have
  2. He doesn’t have
  3. She doesn’t have
  4. It doesn’t have
  5. You don’t have
  6. We don’t have
  7. They don’t have

Do/Does + Have
Does should be followed by he,she,it
Do should be followed by you,we,they

Does he have a friend?
Does she have a friend?
Does it have a friend?

Do you have a friend?
Do we have a friend?
Do they have a friend?

Can I/Could I/May I

  • All are used for getting permission
  • May I is more polite than other two

E.G.
May I help you?
Can I help you again?
Could I Call you Later?
Could I borrow some money?
Can I go?
May I speak to Mr.Kim?
May I go to the bathroom?

Can I and Could I are almost similar
May I is more polite while speaking to someone who is more authoritative or superior than you

May I help you (Mostly heard from shop keepers)

Borrow/Lend Me
Use lend when you are giving money or items to someone.Use borrow when you are taking money or items from someone

You borrow something from somebody. In other words, you take something from someone for a limited time.

You lend something to somebody. In other words, you give something to someone for a limited time.

Wrong
Can I borrow Me your pencil?
Can I borrow your pencil?

Right
Can you lend me your pencil? (or)
Is it ok if I borrow your book?
Can I borrow your umbrella?
May I borrow some money?
Please lend me a pen?
I Lent my baking tin to Emily ages ago and I still haven’t got it back.

If you ask someone to give something or if you give someone – Lend or Lent
If you ask to get something to someone – borrow

An obsolete reference is one that is kept around but will never be used, preventing the object it refers to from being eligible for garbage collection, thus causing a memory leak.

Manually Setting to NULL
Nulling out a reference to remove obsolete references to an object is good, but one must not overdo it. The best way to eliminate an obsolete reference is to reuse the variable in which it was contained or to let it fall out of scope.

Lets take a Simple Stack implementation as in effective Java

public Object pop() {
    if (size == 0)
        throw new EmptyStackException();
    Object result = elements[--size];
    elements[size] = null; // Eliminate obsolete reference
    return result;
}

In the above code you can see that the stack size is shrinked when ever a pop operation is carried out and is set to null allowing the garbage collector to access the unused space to reclaim

Using WeakHashMap
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.

How HashMap Works

// Java program to illustrate 
// Hashmap 
import java.util.*;
class HashMapDemo
{
    public static void main(String args[])throws Exception
    {
        HashMap m = new HashMap();
        Demo d = new Demo();
         
        // puts an entry into HashMap
        m.put(d," Hi "); 
         
        System.out.println(m); 
        d = null;
         
        // garbage collector is called
        System.gc();
         
        //thread sleeps for 4 sec
        Thread.sleep(4000); 
         
        System.out.println(m);
        }
    }
    class Demo
    {
        public String toString()
        {
            return "demo";
        }
         
        // finalize method
        public void finalize()
        {
            System.out.println("Finalize method is called");
        }
}

Output

{demo=Hi}
{demo=Hi}

How WeakHashMap Works

// Java program to illustrate 
// WeakHashmap 
import java.util.*;
class WeakHashMapDemo
{
    public static void main(String args[])throws Exception
    {
        WeakHashMap m = new WeakHashMap();
        Demo d = new Demo();
         
        // puts an entry into WeakHashMap
        m.put(d," Hi "); 
        System.out.println(m);
         
        d = null;
         
        // garbage collector is called
        System.gc(); 
         
        // thread sleeps for 4 sec
        Thread.sleep(4000); .
         
        System.out.println(m);
    }
}
 
class Demo
{
    public String toString()
    {
        return "demo";
    }
     
    // finalize method
    public void finalize()
    {
        System.out.println("finalize method is called");
    }
}

Output

{demo = Hi}
finalize method is called
{ }