Wednesday, September 2, 2015

RDBMS vs NoSQL

Nice article. So rather writing it from scratch. I thought sharing this with everyone. RDBMS vs NoSQL

Thursday, August 27, 2015

Composition vs Inheritance in OOPS

Composition - Having a Has-A relationship and simply uses instance variable that are references of other objects.
Inheritance - Having IS-A relationship and simply access state and behaviour of other object by inheriting it. 

Ex. Hyundai is-A Car (Inheritance) Has-A Engine (Composition)


 Properties
Inheritance
Composition
Flexibility
When you use Inheritance, you have to define which class you are extending in code; it cannot be changed at runtime. 
Composition you just define a Type which you want to use, which can hold its different implementation.
Code Reuse
Inheritance you can only extend one class, which means you code can only reuse just one class, not more than one. 
If you want to leverage functionalities from multiple classes, you must use Composition.
Unit Testing
When you design your class using Inheritance, you must need parent class in order to test child class. There is no way you can provide mock implementation of parent class.
When you design classes using Composition they are easier to test because you can supply mock implementation of the classes you are using
Final Classes
You cannot inherit final classes, hence you cannot reuse code of final class
Composition allows code reuse even from final classes
Encapsulation
Inheritance breaks encapsulation because in case of Inheritance, sub class is dependent upon super class behaviour. If parent classes changes its behaviour than child class is also get affected. If classes are not properly documented and child class has not used the super class in a way it should be used, any change in super class can break functionality in sub class.
Composition doesn't break encapsulation.If main class changes its behaviour then calling class doesn't get affected. 

  • Don't use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.
  • Don't use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces.

Wednesday, August 5, 2015

Singleton object creation

1 ) Singleton with eager loading

import java.io.Serializable;
import java.lang.reflect.Constructor;

public class SingletonTest implements Serializable {

private static final long serialVersionUID = 5287483952638645154L;
private final static SingletonTest INSTANCE = new SingletonTest();

private SingletonTest() {
if (INSTANCE != null) {
throw new IllegalStateException("Inside SingletonTest(): SingletonTest " + "instance already created.");
}
System.out.println("Inside SingletonTest(): Singleton instance is being created.");
}

public static SingletonTest getInstance() {
return INSTANCE;
}

@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

// This method is called immediately after an object of this class is
// deserialized.
protected Object readResolve() {
// Instead of the object we’re on, return the class variable singleton
return INSTANCE;
}
}

To test this use given main method

public static void main(String[] args) {
//System.out.println(SingletonEnum.INSTANCE);
try {
System.out.println("Inside main(): Getting the singleton instance using getInstance()...");
System.out.println(SingletonTest.getInstance());
Class clazz = SingletonTest.class;
Constructor cons = clazz.getDeclaredConstructor();
cons.setAccessible(true);
SingletonTest s2 = cons.newInstance();
System.out.println(s2);

}
catch (Exception e) {
e.printStackTrace();
}
}

2) Singleton with Lazy Loading
package com;

public class SingletonLazy {
private SingletonLazy() {
}
private static SingletonLazy INSTANCE = null;
public static SingletonLazy getInstance() {
if (INSTANCE == null) {
synchronized (SingletonLazy.class) {
if (INSTANCE == null) {
INSTANCE = new SingletonLazy();
}
}
}
return INSTANCE;
}
}

3) Singleton with Enum
public enum SingletonEnum {
INSTANCE;

private SingletonEnum() {
System.out.println("Here");
}
}

How to create Immutable Class in java

The following rules define a simple strategy for creating immutable objects. Not all classes documented as "immutable" follow these rules. This does not necessarily mean the creators of these classes were sloppy — they may have good reason for believing that instances of their classes never change after construction. However, such strategies require sophisticated analysis and are not for beginners.
1.    Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
2.    Make all fields final and private.
3.    Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
4.    If the instance fields include references to mutable objects, don't allow those objects to be changed:
o    Don't provide methods that modify the mutable objects.
o    Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.


You can still create immutable object by violating few rules, like String has its hash code in non-final field, but it’s always guaranteed to be same. No matter how many times you calculate it, because it’s calculated from final fields, which is guaranteed to be same. This required a deep knowledge of Java memory model, and can create subtle race conditions if not addressed properly. In next section we will see simple example of writing immutable class in Java. By the way, if your Immutable class has lots of optional and mandatory fields, then you can also use Builder design pattern to make a class Immutable in Java.

How to create immutable object

Benefits of Immutable Classes in Java

Immutable classes’ offers several benefits, here are few to mention:
1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because it’s easier to share between multiple threads without external synchronization.
3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers.  You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.

Tuesday, August 4, 2015

How HashMap works in Java

First of all, lets keep one thing in your mind that, every collection API internally implements either Array or LinkedList to store objects. Primary Hashmap works in Hashing principle and calculating Hashcode is a key. unique hashcode for each object will ensure fast processing. So before implementing any collection API, strong knowledge of Hashcode and equals method is must.

Now, I will try to explain step by step, how Hashmap works.
1) Let's Create an Instance of Hashmap 
Map
Here, as soon as you write new HashMap JVM call default Constructor of HashMap which internally calls Parameterized constructure of HashMap with default size of 16. This constructor Initalize the ElementArray with Default Size and set basic parameters like elementCount, loadfactor (0.75f).

ElementArray is nothing but an Array of Entry Type. 
Now what is an Entry ? 
Entry is an static inner class of HashMap which is being used to hold the Key and Value with equals and Hashcode implemented, 
So when you put something in to Map, it is an Entry object which is being stored in ElementArray.
Syntax - 
static class Entry extends MapEntry 

Creating Entry object and putting it into Array.

Entry createHashedEntry(K key, int index, int hash) {
        Entry entry = new Entry(key, hash);
        entry.next = elementData[index];
        elementData[index] = entry;
        return entry;

    }
So, now HashMap object created and memory allocated to store objects in terms of key and value.
2) Put object into HashMap - 
map.put(object, object);
Above statement calls put method of HashMap. 
public V put(K key, V value) which internally calls putImpl(K key, V value) and return type is Value.However, there is no use of returned value but still if you call it put and wanted to assign reference to it you can do that.
put method, first checks if provided key is null, as HashMap supports one Null key, you can very well use Null as key. If key is Null then it first checks if Entry object having Null as key is already available in elementArray.  Null as key get stored in index 0 all the time. So it directly fetches from elementArray[0] whenever requested.
If no Entry object found then it creates new Entry object having Null as key and value ( Whatever we have passed) and store it into index 0 of elementarray.
If Key is not null then it first calculate the Hashcode of key and then the index. Once location in Array identified, Entry objects,get created and inserted in the same location.
As Hashcode can be same for two objects, depends on hashing algorithm applied, you can land up in a situation where two keys having same Index in array. This is called collision and to handle this Java has implemented LinkedList concept for storing entry objects.
Each entry object having a next field which holds the reference of another key having same hashcode.
As soon as array 75% filled ( load factor 0.75), array size gets doubled.
To avoid this programmer should write strong hashing algorithm while overriding hashcode. Making immutable object as key can solve the problem and improve the performance.

3) Get Object from HashMap
map.get (key)
If provided key is null then directly entry object will be retrieved from elementArray[0] and will check if key is null, once get value of entry will be returned.
If provided key is not null then first it will calculate hashcode of key and identifies the location (Index) . Will extract the Entry Object from elementArray[index]. It will iterate whole entry object as it maintain LinkedList and compare hashcode of stored key and provided key, if it is same then will apply equal method to compare the content of key. If both are same it will return the value of given key.
Sample code of getting object- 
int hash = key.hashCode();
        int index = hash & (elementData.length - 1);
int storedKeyHash = keyHash & 0xFFFFFFFE;
Entry m = elementData[index];
while (m != null && (m.storedKeyHash != storedKeyHash || !key.equals(m.key))) {
m = m.next;
}

Note - String, Integer and other wrapper classes are considered as good key

String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutability is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety, If you can  keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during retrieval of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.