Tuesday 28 October 2014

Java Class Loaders

        Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.



Classloaders and their explaination -  
  • Bootstrap (primordial) - No Loads JDK internal classes, java.* packages. (as defined in the  sun.boot.class.path system property, typically loads rt.jar and i18n.jar). Classes loaded by Bootstrap  class loader have no visibility into classes loaded by its descendants (i.e. Extensions and Systems  class loaders).

  • Extensions - Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
  • System - No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options). The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).


Monday 27 October 2014

Tomcat HTTP to HTTPS redirect

The following post shows how to easily redirect HTTP to HTTPS in Tomcat servlet container that it always requires secure connection. It was assumed that the following TCP ports are used for that purpose:

8080: for HTTP
8443: for HTTPS


  • Edit you server.xml file located in conf folder of tomcat installation directory

<Connector port="8080" protocol="HTTP/1.1"
     redirectPort="443"/>

<Connector port="8443" protocol="HTTP/1.1"
    SSLEnabled="true"
    scheme="https" secure="true"
    clientAuth="false"
    sslProtocol="TLS"
    keystoreFile="conf/keystore"
    keystorePass="s00perSeeekrit"/>

  • Add below entry in web.xml of your tomcat conf folder.
<security-constraint>
     <web-resource-collection/>
         <web-resource-name>HTTPSOnly</web-resource-name>
         <url-pattern>/*</url-pattern
     </web-resource-collection>
     <user-data-constraint>
         <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint>
</security-constraint>
  • Restart Tomcat.
You're done! The Tomcat always requires secure connection now...

Friday 24 October 2014

Singleton Design Pattern in java

This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.


There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

Implementing Singletons:


The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:
// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}
Here is the main program file where we will create singleton object:
// File Name: SingletonDemo.javapublic class SingletonDemo {
   public static void main(String[] args) {
      Singletontmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}
This would produce the following result:
demoMethod for singleton


Interview Questions & Answers on singleton class:


Question: What is double checked locking in Singleton?
Answer: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization.

public static Singleton getInstance(){
     
if(_INSTANCE == null){
         
synchronized(Singleton.class){
         
//double checked locking - because second check of Singleton instance with lock
                
if(_INSTANCE == null){
                    _INSTANCE = 
new Singleton();
                
}
            
}
         
}
     
return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.


Question: How do you prevent for creating another instance of Singleton using clone() method?
Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.


Question: What is lazy and early loading of Singleton and how will you implement it?
Answer: As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.


If you have