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

Single Dispatch

SingleDispatch.java

public class SingleDispatch 
{
	public void print()
	{
	  System.out.println("Single Dispatch");	
	}

 	public static void main(String[] args) 
	{
	  SingleDispatch objSingleDis = new SingleDispatch();
 	  objSingleDis.print();	
        }
}

Dynamic Dispatch
Dynamic dispatch is the same thing which we do in strategy pattern.The actual method which is called is known at the runtime

Account.java

public interface Account 
{
  public void calculateinterest();
}

SavingsAccount.java

public class SavingsAccount implements Account
{
	@Override
	public void calculateinterest() {
		System.out.println("Intrest is 8%");
	}
}

LoanAccount.java

public class LoanAccount implements Account
{
	@Override
	public void calculateinterest() {
		System.out.println("Intrest is 11.5%");
	}

}

CalculateInterest.java

public class CalculateInterest 
{
	public static void main(String[] args) 
	{
		Account objSavAcc = new SavingsAccount();
		Account objLoanAcc = new LoanAccount();
		
		objSavAcc.calculateinterest();
		objLoanAcc.calculateinterest();
	}
}

What is Multiple Dispatch
Account.java

public class Account 
{	
	public void calculateinterest() {
		System.out.println("Intrest is 11.5%");
	}
	
	public void calculateinterest(int prePayment) {
		System.out.println("Intrest is 11.5% with prePayment");
	}
	
	public void calculateinterest(int prePayment, boolean floatingIntrest) {
		System.out.println("Intrest is 11.5% with floatingIntrest");
	}
}

Now in the above example we have a Account class where the functions are overloaded.Now when the code gets executed then the methods are chosen based on the parameters passed.

public class CalculateInterest 
{
	public static void main(String[] args) 
	{
		Account objAcc = new Account();		
		
		objAcc.calculateinterest();
		objAcc.calculateinterest(23);
		objAcc.calculateinterest(23, true);
	}
}

Output

Intrest is 11.5%
Intrest is 11.5% with prePayment
Intrest is 11.5% with floatingIntrest

Now Java doesn’t supports multiple dispatch as above.The above code is an example of overloading.

Overloading vs Multiple Dispatch
The Difference between overloading and Multiple Dispatch is when the method to be called is decided at compile time then it is Overloading, if the method is decided at runtime then it is multiple dispatch

What is Double Dispatching?
In Double Dispatching the choosing of the method happens dynamically twice.In the below example the method is chosen similar to strategy pattern first time during call of viewReport method and again during choosing which printReport method to be called based on the class type its is called similar to

Staff.java

public interface Staff 
{
	void viewReport(Report objReport);
}

Teacher.java

public class Teacher implements Staff
{
	@Override
	public void viewReport(Report objReport) 
	{
                System.out.println("View Report of Teacher");
		objReport.printReport(this);
	}
}

Principal.java

public class Principal implements Staff
{
	@Override
	public void viewReport(Report objReport) 
	{		
                System.out.println("View Report of Principal");
		objReport.printReport(this);		
	}
}

Report.java

public class Report 
{
	public void printReport(Teacher objTeacher)
	{
		System.out.println("Can print report of her class"); 
	}
	
	public void printReport(Principal objPrincipal)
	{
		System.out.println("Can print report of all the class");
	}
}

ShowReport.java

public class ShowReport 
{
	public static void main(String[] args) 
	{
		Principal objPrincipal = new Principal();
		Teacher objTeacher   = new Teacher();
		objPrincipal.viewReport(new Report());
		objTeacher.viewReport(new Report());
	}
}

Output.java

View Report of Principal
Can print report of all the class
View Report of Teacher
Can print report of her class

In statically typed languages, including Java, the biggest difference between dispatch and overloading is that overloading is based on the static type of parameters (i.e. the choice of which method is actually called is decided at compile-time), while dispatch is based on the dynamic types (i.e. the decision is made at runtime). (Such languages usually don’t support multiple dispatch.)

Another Example of Double Dispatch is Serialization.In Serialization the class which is Serializable calls the methods with itself as an argument.In the below example the writeObject method dispatches the call back to the ObjectOutputStream thus making this a double dispatch. ObjectOutputStream delegates back MuxPrinter the responsibility of writing its state onto stream. By Doing this ObjectOutputStream has decoupled itself from our object objMuxPrt.

public class MuxPrinter implements Serializable
{

}

MuxPrinter objMuxPrt = new MuxPrinter();
ObjectOutputStream oos = new ObjectOutputStream();
oos.writeObject(objMuxPrt);  

Types (Hierarchy) of Java Class Loaders
Java class loaders can be broadly classified into below categories:

Bootstrap Class Loader
Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.

Extensions Class Loader
JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.

System Class Loader
Java classes that are available in the java classpath are loaded using System class loader.

Why you need class Loaders
Applications written in statically compiled programming languages, such as C and C++, are compiled into native, machine-specific instructions and saved as an executable file. The process of combining the code into an executable native code is called linking – the merging of separately compiled code with shared library code to create an executable application. This is different in dynamically compiled programming languages such as Java. In Java, the .class files generated by the Java compiler remain as-is until loaded into the Java Virtual Machine (JVM) — in other words, the linking process is performed by the JVM at runtime. Classes are loaded into the JVM on an ‘as needed’ basis. And when a loaded class depends on another class, then that class is loaded as well.

When a Java application is launched, the first class to run (or the entry point into the application) is the one with public static void method called main(). This class usually has references to other classes, and all attempts to load the referenced classes are carried out by the class loader.

java.lang.ClassLoader
The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes. Constructors in java.lang.ClassLoader (and its subclasses) allow you to specify a parent when you instantiate a new class loader. If you don’t explicitly specify a parent, the virtual machine’s system class loader will be assigned as the default parent.

  1. The difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock.
  2. Class level lock is one for each class and represented by class literal e.g. String.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java
  3. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block.
  4. One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance.
  5. Synchronized block provide granular control over lock(“very detailed control”, meaning you can control a lot of specific aspects), as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword or class level lock, if its static synchronized method.
  6. Synchronized block can throw throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.
  7. In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.
public class SycnronizationExample 
{

	public synchronized void lockedByThis()
        {
        System.out.println(" This synchronized method is locked by current" instance of object i.e. this");
        }

	public static synchronized void lockedByClassLock() 
        {
	System.out.println("This static synchronized method is locked by class level lock of this class i.e. SychronizationExample.class");
	}

	public void lockedBySynchronizedBlock()
        {
           System.err.println("This line is executed without locking");     
           Object obj = String.class; //class level lock of Stirng class
     
          synchronized(obj)
          {
            System.out.println("synchronized block, locked by lock represented using obj variable");
          }
         }
}

Iterator
Iterator is the interface and found in the java.util package.It has three methods

  1. hasNext()
  2. next()
  3. remove()

Enumeration
Enumeration is also an interface and found in the java.util package .An enumeration is an object that generates elements one at a time. It is used for passing through a collection, usually of unknown size.The traversing of elements can only be done once per creation.

It has following methods

  1. hasMoreElements()
  2. nextElement()

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework.Iterators differ from enumerations by allowing the caller to remove elements from the underlying collection during the iteration.

HashMap vs HashTable

  1. HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
  2. Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
  3. Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator’s own remove method , then the iterator will throw ConcurrentModification Exception.
    Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.
  4. Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.

Similarities Between HashMap and Hashtable

  1. Insertion Order :Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
  2. Map interface :Both HashMap and Hashtable implements Map interface .
  3. Put and get method :Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.
  4. Internal working :Both HashMap and Hashtable works on the Principle of Hashing . We have already discussed how hashmap works in java .

When to use HashMap and Hashtable?
Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .

Multi Threaded Application
We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.

An instance is eligible for garbage collection when null is assigned to it. These are choices made by the JVM implementer.

class Animal 
{
    public static void main(String[] args) 
    {
        Animal lion = new Animal();
        System.out.println("Main is completed.");
    }

    protected void finalize() {
        System.out.println("Rest in Peace!");
    }
}

During compilation process as an optimization technique the Java compiler can choose to assign null value to an instance, so that it marks that instance can be evicted.

In the above class, lion instance is never uses beyond the instantiation line. So the Java compiler as an optimzation measure can assign lion = null just after the instantiation line. So, even before SOP’s output, the finalizer can print ‘Rest in Peace!’. We cannot prove this deterministically as it depends on the JVM implementation and memory used at runtime.

Being an automatic process, programmers need not initiate the garbage collection process explicitly in the code. System.gc() and Runtime.gc() are hooks to request the JVM to initiate the garbage collection process.

When we are writing a performance benchmark we may call System.gc() in between runs

Just before evicting an instance and reclaiming the memory space, the Java garbage collector invokes the finalize() method of the respective instance so that the instance will get a chance to free up any resources held by it. Though there is a guarantee that the finalize() will be invoked before reclaiming the memory space, there is no order or time specified. The order between multiple instances cannot be predetermined, they can even happen in parallel. Programs should not pre-mediate an order between instances and reclaim resources using the finalize() method.Any uncaught exception thrown during finalize process is ignored silently and the finalization of that instance is cancelled.

Similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.

Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.

Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.

Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.

Note : Don’t use StringBuffer unnecessarily, i.e., don’t use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don’t use locks unless it is required.

Simply use StringBuilder unless you really are trying to share a buffer between threads. StringBuilder is the unsynchronized (less overhead = more efficient)

When a String is there and you add use concat like one below

  
 String x = "Java";
 x.concat("Rules !");
 sysout(x);

Now in the above there would be 2 string object created with output Java.When you used append in stringBuilder or stringBuffer the changes were applied over the object itself

  
 StringBuiler x = new StringBuiler("Java");
 x.append("Rules !");
 sysout(x);

the output would be Java Rules !

I will give you an example first:

public interface LoginAuth{
   public String encryptPassword(String pass);
   public void checkDBforUser();
}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

public class DBMySQL implements LoginAuth{
          // Needs to implement both methods
}
public class DBOracle implements LoginAuth{
          // Needs to implement both methods
}
public class DBAbc implements LoginAuth{
          // Needs to implement both methods
}

But what if encryptPassword() is not database dependent, and it’s the same for each class? Then the above would not be a good approach.

Instead, consider this approach:

public abstract class LoginAuth{
   public String encryptPassword(String pass){
            // Implement the same default behavior here 
            // that is shared by all subclasses.
   }

   // Each subclass needs to provide their own implementation of this only:
   public abstract void checkDBforUser();
}

Now in each child class, we only need to implement one method – the method that is database dependent.

Technical Differences

  1. Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no expensive look-up to do. It’s great when it matters such as in embedded devices
  2. Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them.
  3. Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
  4. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
  5. When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.
  6. Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  7. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
  8. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).

Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.

Consider using interfaces if :

You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.

abstract class establishes “is a” relation with concrete classes. interface provides “has a” capability for classes.