Friday, March 21, 2014

CODING Standards

This could be most briefed post in my blog but one of the most important posts.

We are going to talk about most generic and important topic so called "Standards" (which i think to be considered for writing).

In my view, there are no coding standards that to be followed unless you like it. If you ask me write me standards i will write hell of standards. The most important point in developer world should be, the code written by one has to be understandable and able to change by others and the code should be able to evolve with the changes and shouldn't be obsolete in near future atleast .

Few points to consider while coding any kind of program/project.

  • We are capable of doing of miracles with the flexibility and feasibility given by the programming language, IDEs, frameworks, APIs but cleverness lies in how readable is it. So focus on readability.
  • Read the standards provided by the developers. For example Sun/Oracle/etc provided some standards to be followed while writing Java.  The one i like the most is Google java style
  • Every code works unless you find problems in it. Robustness lies in the way it works and how easy to find the issues and fix it.
  • Know what to write where (Read the pros or cons of any standard/usage before applying it otherwise it may go weird.)
  • Configuration v/s Performance. There is a trade of between configuration and performance. If it is too configurable, then it will be less performance and vice versa. (This is not true in all cases).
  • Judge between different ways. There can be different ways to do the same task. Analyze before implementing it. 
  • Time to Live. we heard the time to live only in messaging but developers has to think what is the life time of the code that is being written. Because after some days it may be obsolete because of the evolution of the programming languages and techniques. 
  • Research, research and research. According to me, there should enough research and reason before development, don't develop and research for problem solving. Reason enough to develop. 
Most important point i want to conclude is 
"Read, Research, Understand, Justify and write standard, re-usable and readable code which can evolve with the changing world.".

When you think about most successful frameworks and programs thats the only secret.



Sunday, March 2, 2014

Generics - Java

Generics

The main concept of Generics is to define typed variables and make the compiler to pre-check the types v/s values before actual execution of the program. So, in short, Generic type is a class or an interface which can be parameters for type. 

How to define

Generic is defined by using an angular brace like <T>.
Syntax:
class name<T1,T2,.... >
Example:
List<String> list = new ArrayList<String>();
Most of the classes (In fact all) of Collections are generic. So, when you look at the method of List class.
boolean add(E e);
E could be any type that you have defined while creating the instance of the List.

Points to be noted

So, there are couple of points to be noted before getting into the details of the generics.

What types:

Instead of looking for what types are allowed lets look at what types are not allowed because all types are allowed expect for primitives ;) 

How many:

There is no limit for the number of types that can be defined. We can define any number of types.

Where to define:

Generics can be defined for
  • Classes
  • Interfaces
  • Constructors
  • Methods

Uses

  • Introduce strong types for the custom classes, collections
  • Remove the explicit casting of objects.
  • Autoboxing / Autounboxing features can be used directly with generics.
  • Wildcards works (? extends and ? super)with generics which made the hierarchy typing as easy.

Explanation

Let's see the uses with an example for each

Strong Types and Casting

Let's define a List.
//Normal 
List oList = new ArrayList();

//Generic type
List<String> gList = new ArrayList<String>();
Here
  • aList - can store any type of element in list object and developer has to be careful enough while reading and writing into it. 
  • gList - can store only String types and compiler throws error while writing elements into it other than Strings.

Reading:
aList.add("name"); //Allowed
aList.add(1); //Allowed

gList.add("name"); //Allowed
gList.add(1) //Now allowed
Writing:
//aList operations
String str = (String)aList.get(0); //Requires explicit casting
Integer aInt = (Integer)aList.get(1); //Requires explicit casting

Integer incorrect = (Integer)aList.get(0); //No compilation error but throws runtime exception.

//gList operations
String a = gList.get(0) //No explicit casting.

Integer b = gList.get(1) //Not allowed. Compiler throws error. but still you can explicitly convert it to Integer.
Iterating:
//Using iterator
for (Iterator iter = gList.iterator(); iter.hasNext();) {
  String s = iter.next();
  System.out.print(s);
}

//Using foreach
for (String s: gList) {
   System.out.print(s);
}

Autoboxing / Autounboxing

We can define generics for any type expect for built-in types but autoboxing and unboxing works with generics like below without any issues.
//Autoboxing
Set set = new HashSet();
set.add(1);
set.add(3);

//Autounboxing
for(int s : set)
{
  System.out.println(s);
}

Wildcards

Even if we define a class with generic types, sometimes we may need to use them based on the hierarchy. It can be either a subclass declaration or super class declaration. The keywords for the wildcards used are
  • ? extends T - Any class which extends T
  • ? super T - Any class which is super to T
void eat(List<? extends Fruit> fruits); //This method accepts parameter any list of objects which is child of Fruit
void eat(List<? super Fruit> fruits); //This method accepts parameter any list of objects which is parent of Fruit 
Happy Learning!!!!

Sunday, February 23, 2014

Instrumentation using AspectJ

Many of us start writing the code without worrying about how performant it will be? Once the program started working, we will be making changes like adding logs, timing statements to check the performance.
I too used to do the same before i came across AspectJ (Even though it was there since 2003, i came across it very recently).
AspectJ is available as
  1. Eclipse plugin
  2. Standalone compiler 
Let me show you an example on how to check the execution time of a method in a Test program.

Aspect

It's pretty simple. It is more or less a Java Class with special keywords. The following is the aspect which will be called before and after a method call
mport org.aspectj.lang.Signature;

public aspect MethodExeuctionTime {
    pointcut traceMethods() : (((execution(* com.instrument.test.CommonProcessor.test(..)))
            || (execution(* com.test.InstrumentProcessor.process1(..)))
            || (execution(* com.instrument.test.CommonProcessor.test(int)))
            || (execution(* com.test.InstrumentProcessor.process3(..))))
         && !cflow(within(MethodExeuctionTime)));

    before(): traceMethods(){
        Signature sig = thisJoinPointStaticPart.getSignature();
        String name = Thread.currentThread().getName();
        TimingUtils.addStart(sig.getName(), sig.getDeclaringTypeName(), System.currentTimeMillis(),name );
    }

    after(): traceMethods(){
        Signature sig = thisJoinPointStaticPart.getSignature();
        String name = Thread.currentThread().getName();
        TimingUtils.addEnd(sig.getName(), sig.getDeclaringTypeName(), System.currentTimeMillis(), name);
    }
}

Explanation:

  • pointcut is a rule where the aspect to be implemented. Syntax is pointcut <method-name> : {conditions to execute}
  • Conditions - Here in the example says during the execution of methods provided.
  • Conditions can be specified using wild chars like (*).  Logical expressions (|| or &&).
  • Finally defined the actual method. Here we see that there are two definitions of method traceMethods (In fact they are not definitions). Which says what code to execute before the method call and after method call respectively.
TimingRecord.java and TimingUtils.java are as follows
public class TimingRecord {
    private long startTime;
    private long endTime;
    private String methodName;
    private String packageName;
    private String threadName;

    public TimingRecord(long startTime, String methodName, String packageName, String threadName) {
        this.startTime = startTime;
        this.methodName = methodName;
        this.packageName = packageName;
        this.threadName = threadName;
    }
    //getters and setters
}
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class TimingUtils {

    private static Map map = new HashMap();

    public static void addStart(String methodName, String type, long time, String threadName){
        String key = threadName+type+methodName;
        TimingRecord record = new TimingRecord(time, methodName, type, threadName);
        Stack stack = (Stack) map.get(key);
        if(stack == null)
            stack = new Stack();
        stack.push(record);
        map.put(key, stack);
    }

    public static void addEnd(String methodName,String type, long time, String threadName){
        String key = threadName+type+methodName;
        Stack stack = (Stack) map.get(key);
        if(stack == null || stack.size() == 0)
            return;

        TimingRecord e = (TimingRecord) stack.pop();
        if(e != null)
        {
            long millis = time - e.getStartTime();
            System.out.println("Time Taken to Execute : Type : "+type+" Thread: "+threadName+" Method : "+methodName + " Time : "+ millis +" ms.");
        }
        map.put(key, stack);
    }
}

How to Compile

Now to compile this, set ajc in your PATH and aspectjrt.jar in CLASSPATH and run the following command
  • ajc * -d ../classes -outxml -outjar aspectj.jar
This creates a jar named aspectj.jar with an xml file ajc-aop.xml inside it which tells whats the aspect name to be injected.

How to Run

  • Add the following lines to the command line of your program execution.
    • -javaagent:<path-to-aspectjlib>/aspectjweaver.jar
    • -cp <class-path>:<path-to-project>/aspectj.jar

Sample Program

Look at the following example program
package com.test;

import com.instrument.test.CommonProcessor;

public class InstrumentTest extends Thread
{
    public static void main(String[] args)
    {
        InstrumentTest i1 = new InstrumentTest();
        i1.setName("I1");
        InstrumentTest i2 = new InstrumentTest();
        i2.setName("I2");
        InstrumentTest i3 = new InstrumentTest();
        i3.setName("I3");
        i1.start();
        i2.start();
        i3.start();
    }

    public void run()
    {
        try {
            System.out.println("Started Processing : "+getName());
            InstrumentProcessor p1 = new InstrumentProcessor();
            p1.process1();
            p1.process2();
            p1.process3();
            System.out.println("Completed Processing : "+getName());
        } catch(Exception e) {
            
        }
    }
}
package com.test;

public class InstrumentProcessor
{
    public void process1() throws Exception {
        Thread.sleep(3000);
    }
    
    public void process2() throws Exception {
        Thread.sleep(4000);
    }
    
    public void process3() throws Exception {
        Thread.sleep(5000);
    }
}

Run the program 

Without instrumentation 

  • The log will be similar to
Started Processing : I1
Started Processing : I3
Started Processing : I2
Completed Processing : I2
Completed Processing : I1
Completed Processing : I3

With Instrumentation 

  • Add the parameters mentioned above (-javaagent and aspectjrt.jar,aspectj.jar to class path). 
  • The log will be
Started Processing : I1
Started Processing : I3
Started Processing : I2
Time Taken to Execute : Type : com.test.InstrumentProcessor Thread: I3 Method : process1 Time : 3006 ms.
Time Taken to Execute : Type : com.test.InstrumentProcessor Thread: I2 Method : process1 Time : 3006 ms.
Time Taken to Execute : Type : com.test.InstrumentProcessor Thread: I1 Method : process1 Time : 3006 ms.
Time Taken to Execute : Type : com.test.InstrumentProcessor Thread: I1 Method : process3 Time : 5001 ms.
Time Taken to Execute : Type : com.test.InstrumentProcessor Thread: I2 Method : process3 Time : 5001 ms.
Completed Processing : I2
Time Taken to Execute : Type : com.test.InstrumentProcessor Thread: I3 Method : process3 Time : 5003 ms.
Completed Processing : I1
Completed Processing : I3

There are so many other cases you can instrument using AspectJ. This is just one of them.

Happy Learning!!!!!

Monday, January 13, 2014

How HashMap Works

HashMap stores the values in key-value pair and works on the concept of hashing.

Hashing

Hashing is a function which generates a unique value using some algorithms and functions. The first and foremost rule of hashing function is it has to generate the same hash always for the same value.

HashMap

HashMap as mentioned earlier, works on Hashing.
  • It uses a hash table for storing the values in key-value pair. 
  • table is an linked list of type Entry (an inner class) which stores the entries for the same hashCode.
  • It can store key as null (only one).
  • It has two methods get and put for storing and retrieving the values.

Hashing in HashMap

  • To generate the hash value, we have to implement hashCode method for the key.
  • HashMap does one more level of hashing because it may be possible that our implementation may not generate unique value of hash always [As unique value of hash to be generated always].
  • Get the hashCode value defined and performs the hashing on top of it as below.
    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
        h ^= k.hashCode();
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

What equals() does?

  • The uniqueness of a key is decided both on equals and hashCode methods.
  • The hash is used for deciding the index of the bucket to store the value. 
  • equals method is used to decide the equality of the values. 
  • Two values having the same hashCode may not be equal. Those values are stored as an array in the same bucket. 
  • But, two values which are equal (true with equals method) must have same hashCode
The following diagram explains the overview of objects stored in the HashMap

  • HashMap internally stores the value in a list of buckets (named table) of type Entry.
  • Each bucket (Entry) is a linked list of key-value pairs of same hashCode.
  • Current key-value pair has a link to next entry 
  • In the above hashMap, 
    • There are two entries with hashCode H1 and three entries with hashCode H9 which are linked list
    • Only one key/value pair stored for H14 and H16
    • Other buckets are empty. 
  • While storing or retrieving a value using a key. HashMap does the following
    • Calculates the hashCode for the key 
    • Finds the bucket for the key.
    • Creates the bucket (If not exist) and stores the values in the linked list for the particular bucket [In case of put method]
    • If bucket not found, returns null. Otherwise parse through the linked list for that particular bucket and finds the entry for the key[In case of get method].

How get method works

Look at the get method of HashMap
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);
        return null == entry ? null : entry.getValue();
    }

Only three steps

  1. It checks for null. If the key is null, then returns the value which stored at null key.
    1. Value for null key is stored at location 0. Returns null if size is 0 otherwise value at null.
  2. Gets the bucket entry for the key.
    1. Performs hash of the key[as in above code of hash]. 
    2. Find the bucket for that entry and parse through the table (linked list) and finds the value. 
  3. If no entry found, returns null otherwise returns the value at the entry.

How put method works

The put method code is as follows
    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }
Put method also works same as get method but little difference
  • If key is null, adds the value at null key (Index 0).
  • Get the bucket entry for the key.
    • Performs hash of the key[as in above code of hash]. 
    • Finds the entry with hashCode. If not there, creates it.
  • Stores the value in the particular bucket and links to the previous element in the bucket(linked list).
One Note to remember that, put method always returns the old value present at the key. If it's newly stored then returns null.

Size of HashMap

  • HashMap initially will be created with default capacity of 16. 
  • We can explicitly specify the size of hashMap with an argument (int value)
  • HashMap can have a maximum capacity of 1073741824
Happy Learning!!!!!

Saturday, January 4, 2014

Comparable v/s Comparator

Comparable and Comparator are the interfaces used for sorting the elements in the collection. To sort the data in collection either, the data object in the collection has to implement Comparble interface or an extra object to be passed as an parameter to the sort method which implemented Comparator.
Collection.sort method
public static <T extends Comparable<? super T>> void sort(List<T> list) //Using comparable 
public static <T> void sort(List<T> list, Comparator<? super T> c) //Using comparator

Example using Comparable interface

Object implemented Comparable

package com.test.collection;

public class Person implements Comparable<Person> {
   private long id;
   //Getters and Setters
   public int compareTo(Person o) {
      return (int) (getId() - o.getId());
   }
}

How to sort

Create a list of Persons and use Collections.sort method to sort the elements. 
package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CustomSort {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(10));
        list.add(new Person(2));
        list.add(new Person(15));
  
        System.out.println("Elements before sorting : ");
        for(Person i : list)
           System.out.print(" "+i.getId());
        Collections.sort(list); 
        System.out.println("\nElements after sorting : ");
        for(Person i : list)
           System.out.print(" "+i.getId());
    }
}

Output will be

Elements before sorting : 
 10 2 15
Elements after sorting : 
 2 10 15

Example Using Comparator interface

Student Object - Which is used in Collection 

package com.test.collection;

public class Student {
     private long id;
     public Student(long id) {
       this.id = id;
     }
     //Getters and setters
}

StundetComparator class - Implementing Comparator interface of type Student 

package com.test.collection;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {
   public int compare(Student o1, Student o2) {
        return (int) (o1.getId() - o2.getId());
   }
}

How to sort

package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CustomSort {
    public static void main(String[] args) {
      List<Student> list = new ArrayList<Student>();
      list.add(new Student(10));
      list.add(new Student(2));
      list.add(new Student(15));
  
      System.out.println("Elements before sorting : ");
      for(Student i : list)
         System.out.print(" "+i.getId());
      Collections.sort(list,new StudentComparator()); 
      System.out.println("\nElements after sorting : ");
      for(Student i : list)
         System.out.print(" "+i.getId());
   }
}

Output will be

Elements before sorting : 
 10 2 15
Elements after sorting : 
 2 10 15

Comparision

The implementation looks very similar, lets see the similarities and differences between them
Description Comparbale Comparator
Package java.lang.Comparable java.util.Comparator
Implementation
Need to implement in the same where which to be compared. 
Need to implement in separate Class
Arguments
Takes only one argument as the same type where it is implemented. Need to compare with itself and return an integer value
Takes two arguments of same type and should returns an integer value after comparing them.
Collection.sort
No extra arguments are required during sort. Collection.sort uses the compareTo method implemented to sort
Collection.sort requires this object as second argument to sort the Collection which is passed as first argument
Note: The Comparator should be of same type as the Collection.
Sorting
Always sort based on the compareTo method
Sorting will be done based on the comparator object passed in the second argument. So several Comparators can be created with each has it’s sorting logic. Based on the criteria, we can pass any comparator which is required.

Happy Learning!!!