Wednesday, August 5, 2015

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.

Thursday, January 2, 2014

How to configure Interceptor in Struts2

1) Do following configuration in struts.xml
        <!--If Single interceptor -->
        <struts>
                <package name="default" namespace="/" extends="struts-default" >
                        <interceptors>    
                                <interceptor name="testInterceptor"   class="com.test.interceptors.TestInterceptor">    
                                </interceptor>    
                        </interceptors>
                        <action name="testAction" class="com.test.action.TestAction"
                                        method="execute">
                                        <interceptor-ref name="testInterceptor"></interceptor-ref>
                                        <result name="success">/Test.jsp&lt;/result>
                                </action>
                        </package>
                <!-- Add packages here -->
        </struts>
        <!--If Multiple interceptors then prepare a Stack -->    
        <struts>
                <package name="default" namespace="/" extends="struts-default" >
               
                        <interceptors>
                                <interceptor name="testInterceptor"   class="com.test.interceptors.TestInterceptor"/>    
                                <interceptor name="testInterceptor1"   class="com.test.interceptors.TestInterceptor1"/>        
                                <interceptor-stack name="basicStack">
                                        <interceptor-ref name="testInterceptor" />
                                        <interceptor-ref name="testInterceptor1" />    
                                </interceptor-stack>
                        </interceptors>
                        <action name="testAction" class="com.test.action.TestAction"
                                        method="execute">
                                        <!-- <interceptor-ref name="basicStack"></interceptor-ref>-->
                                        <result name="success">/Test.jsp/result>
                        </action>
        </package>
                <!-- Add packages here -->
        </struts>
       
2) Write Interceptor Class
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class TestInterceptor implements Interceptor {
        @Override
        public String intercept(ActionInvocation arg0) throws Exception {
                //Write your Specific code here.
                return SUCCESS;
        }      
}

Monday, December 23, 2013

How to Integrate Struts2.x in web application

Perform following steps to integrate Struts2.x.


1) Download struts2.3 from struts.www.apache.org/download.cgi‎ website. You will be getting couple of jars, however you no need to take all jars in your application.


2) Copy following jars in WEB-INF\lib folder


   1. struts2-core-2.3.15.3.jar
   2. xwork-core-2.3.15.3.jar
   3. ognl-3.0.6.jar
   4. javassist-3.11.0.GA.jar
   5. commons-lang3-3.1.jar
   6. commons-io-2.0.1.jar
   7. core-0.6.2.jar
   8. Xecers.jar
   9. xalan.jar

 3) Configure FilterDispatcher in the web.xml file to intercept each and every http request and response


<filter>
      <filter-name>struts2</filter-name>
      <filter-class<org.apache.struts2.dispatcher.FilterDispatcher
</filter-class
>

</filter>
 <filter-mapping>
      <filter-name>struts2
</filter-name>
      <url-pattern>/*</url-pattern>
 </filter-mapping>

4) Place Struts.xml file in WEB-INF\classes file and configure action in xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="Test" extends="struts-default">
    
      <action name="testAction" class="com.test.TestAction" method="execute">
     <result name="success">/test/Test.jsp</result>
     </action>

   </package>
   <-- more packages can be listed here -->

</struts>

5) Write TestAction class file which will invoke execute method.

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext

public class TestAction extends ActionSupport {
    private String name;
    public String execute() throws Exception {
            System.out.println("TestAction" + name);
                        return SUCCESS;
        }
    public String getName(){
       return name;
    }
    public void setName(){
      this.name = name;
    }
}

 6) Write Test.jsp file and use value stack to take values from response
<%@page import="com.opensymphony.xwork2.util.ValueStack"%>
<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@page import="com.opensymphony.xwork2.ognl.OgnlValueStack"%>
<%
    ValueStack stack = ActionContext.getContext().getValueStack();
    String name = (String) stack.findValue("name");
    System.out.println("Name :"+name);
%>
<html>
    <body>
        <form method="post" action ="TestAction.action">
            <--- Write any HTML code which suites you
            use ognl for using tag or use struts inbuild tags.
            or use free form html tags. Its up to developer-->
        </form>
    </body>
</html>

7) After Prepare war file and deploy in the server.


Issues which you can see -

1) Sometimes Jar files conflict happens and that is too because of either classpath or server used.
2) IF you see xml parser issue then check your lib folder its quite possible that you are using xml jar file which is conflicting with server parsing jar file.in that case write servletcontextlistener and load you jar file during server startup.

Wednesday, March 6, 2013

Dhoni as Test Captain.......

There is a lot talk about Dhoni as a Test cricket captain.Victory in the Hyderabad Test has made MS Dhoni the most Successful captain in Indian cricket, with 22 Test wins. But one thing comes in my  mind that  Is he really the best Test Captain India ever had ? For me, He is successful in terms of victories but he is not Best Test captain. When we talk about Number's then definitely  Dhoni has given a result but when we talk about best as captain then we need to be subjective and need to look each and every aspects like. 
  1.  How many win came in overseas. 
  2. What kind of team composition captain is having.
  3. Team is playing against which opponent
  4. Is captain leading from the front when team is down.
  5. Captain grooming players who can steal the show independently.
There will be more aspect but I just listed few. Is Dhoni satisfied all the conditions? Lets go by statistics now and we will try to get the answers and  will analyze how well Dhoni done in Test cricket as captain. I will compare him with Ganguly because I personally believe he was better captain than anyone else in India.


Played Won Lost Draw Win (%)
Total 45          22 12 11 48.88
In India 24 17 3 4 70.83
Overseas 21 5 10 6 23



Our of his 22 wins, only three (one each in NZ, SA and WI) have come outside the subcontinent.
Now will have a look against whom we got victory overseas under his captaincy. Dhoni: 5 (New Zealand, Bangladesh, Sri Lanka, South Africa, West Indies) . He has been appointed as captain in 2008 and we all know, other than South Africa and SriLanka, no side was having quality players like India. Now see the Dravid's as captain -  Dravid: 5 Oveseas win (Bangladesh, Pakistan, South Africa, West Indies, England)
Moreover, we recently won 2 matches against the Australia, I am afraid whole Australian squad's test careers run is less than Sachin tendulkar's test runs ? Moreover if we combine the matches played by Australian squad and compare with Sachin's match, you will probably get what I want to say.
The poundings in the away series in England and Australia put him under the scanner.


When Dhoni took over from Kumble India team was winning, it just Kumble taken retirement, so he got the well set team in the plate. They said that Indian team is in transition phase with several greats fading away.But let me tell you all big losses came when all senior were there in the team ( Sachin, Sehwag, Dravid and laxman), this can not be a point to discuss.One who become a great when he handles all these situations and respond strongly.

There are couple of good thing happened under Dhoni's captaincy and we can not deny it.
MS Dhoni  is the only Indian captain who won all his first four Tests as captain.
MS Dhoni  is the only Indian captain who did not lose a Test in his first eleven Tests as captain(11 out of 13 played in India).
MS Dhoni  is the only Indian captain who did not lose a series in his first 12 Test series as captain ( same as above).
MS Dhoni  has recorded a victory on Indian soil against every team that has visited India. India did not play Bangladesh and Pakistan on home soil during his leadership.(Achievement)
MS Dhoni is most successful Wicket Keeper/Batsman Test Captain.
MS Dhoni is cool and calm in the ground but it doesn't always suggest that he is taking correct decision under ext ream pressure.


Let see some other captains record, we will start with Ganguly because he is the only competitor  :)
Played Won    Lost         Draw Win (%)
Total 49         21        13 15 42.87
In India 21         10        3 8 47.61
Overseas 28         11        10 7 39.28

Ganguly has recorded a victory on Indian soil against every team that has visited India except New Zealand. India did not play Bangladesh and Sri Lanka on home soil during his leadership.

Ganguly is also the only Indian captain and the third in history to have led his team to victory after being enforced to follow on - against Steve Waugh's Australia in 2001-02.

Ganguly took over when India had been rocked by match-fixing and needed a strong leader to unite the team. He gave the team the belief that they should never back down from anyone and did so by leading from the front. And he would go to any lengths to back his team. That’s why it is no surprise that Kolkata 2001, India's finest moment, came with Ganguly at the helm. He would just never allow the team to give up. And he won Tests in England and Australia too.

Summary : I am neither against Dhoni nor  supporting Ganguly. My only point is, when we talk about greatness or ability of a captain/person then we need to see all aspects rather just looking the results. Results obviously goes in favor of MS Dhoni but if you see all the angles probably you will agree with me that he needs to do a lot work to proove himself as  Best Test captain of India.