Friday, June 9, 2017

New content on Hadoop & AWS


I will be posting a lot of content on AWS And BIG DATA (HADOOP) starting this month which will be helpful for followers in getting a fair knowledge on them.

Thursday, June 19, 2014

How HashMap Works in Java?

HashMap in Java
HashMap store Key/Value pairs just like HashTable. It is faster than HashTable and accept null values and it is not synchronized. These are the basic fundementals we know about HashMap. However, let us try to go through how Hashmap works in Java.

HashMap works on principle of hashing, we have put(key, value) and get(key) method for storing and retrieving Objects from HashMap. When we pass Key and Value object to put() method on Java HashMap, HashMap implementation calls hashCode() method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object, important point to mention is that HashMap in Java stores both key and value object as Map.Entry in bucket. Then, there is another important concept of Collision detection and Collision resolution in Java HashMap i.e What will happen when two objects have same hashcode?
According to the equals() and hashCode() contract, we know that for two objects to be equal, they need to have same hashcode. However, the oppositeis not true. i.e Two objects with same hashcode need not necessarily be equal. Here, when 2 objects with same hashcode is returned, this condition is called collision detection.

To resolve this collision, we should know that HashMap uses LinkedList to store object i.e the Map.Entry Object which comprises of Key and Value will be stored in a LinkedList. When an object is tried to be retrieved by calling the get(Object key) method, the linked list is traversed and if 2 objects are returned which has same hashCode, then it calls the key.equals() method to find the correct node in the linked list and return its associated value. So, it is very important that we maintain unique/unmodifiable keys.
Therefore, it is nice to remember and follow that using immutable, final object with proper equals() and hashcode() implementation would act as perfect Java HashMap keys and improve performance of Java HashMap by reducing collision. Immutability also allows caching there hashcode of different keys which makes overall retrieval process very fast and suggest that String and various wrapper classes e.g. Integer very good keys in Java HashMap.

Fail-Fast And Fail-Safe Iterators/ConcurrentModificationException

Fail-Fast And Fail-Safe Iterators/ConcurrentModificationException
Quite few times, while iterating over a List or collection and trying to perform some operations, we get ConcurrentModificationException. The idea behind getting to know the true reason for this is to know the type of iterator or to be precise, the type of collection that we are iterating on.
There are 2 types of Iterators:
1. Fail-Fast
2. Fail-Safe

The Fail-Fast iterators are ones which fails (And throws ConcurrentModificationException) when the collection's structure (i.e its size) changes upon iteration i.e whenever we add or remove an item from a collection or whenever a different thread adds/removes an item from a collection which is being interating currently, the ConcurrentModificationException is thrown. Collection Classes in java.util uses Fail-Fast iterators
Fail-Safe iterators are designed to overcome this. The classes in the package java.util.concurrent uses Fail-Safe iterators. i.e they do not throw ConcurrentModificationException when the collection structure i.e size changes while it is being in the middle of iteration
Looking at the example below, we see that Iterators on ArrayList from java. util package throws ConcurrentModificationException when during the iteration, we try to add another item to the ArrayList and hence change the structure of the collection. However, CopyOnWriteArrayList class in java.util.concurrent package uses Fail-Safe interators and hence, they do not throw the exception and are thread safe.
package com.sample.collectionsexamples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class FailFastAndFailSafeIteratorDemo {
 
   public static void main(String[] args) {
     List arrayList = new ArrayList();
     List copyOnWriteArrayList = new CopyOnWriteArrayList<>();
 arrayList.add(10);
 arrayList.add(20);
 arrayList.add(30);
 arrayList.add(40);
  
 copyOnWriteArrayList.add(10);
 copyOnWriteArrayList.add(20);
 copyOnWriteArrayList.add(30);
 copyOnWriteArrayList.add(40);
  
 iterateOperation("CopyOnWriteArrayList",copyOnWriteArrayList);
 iterateOperation("ArrayList", arrayList);
  
 }
 
 static void iterateOperation(String type, List numbers) {
   System.out.println("Iterating and adding item on: "+type);
       Iterator itr = numbers.iterator();
   while(itr.hasNext()) {
  // Add another integer 50 after 40
  // This code to add will fail for ArrayList 
                // throwing ConcurrentModificationException
  // But it works fine for CopyOnWriteArrayList
      if(itr.next() == 40) {
     numbers.add(50);
   }
 }
 System.out.println("Items in the list "+type+" = "+numbers);
} 

}

Tuesday, March 4, 2014

Java 7 new features

1. Java 7 Switch String Support
Until the previous version, Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type. i.e Prior to Java 7, it supported variables and expressions which resolved into int, byte, short or char only (OR) it supported Enums. But now, Java 7 has added supporting String types for Switch statement Case values and with this feature, it will surely save a lot of complex if-else structures and improve the overall code readability. Here is a self explanatory example of Switch with Strings in action. We simply accept the String input and print the corresponding matching case
package com.java7.features;

import java.util.Scanner;

public class Java7SwitchDemo {
    public static void main(String[] args) {
 System.out.println(" Sachin\n Dhoni\n Kumble\n ");
 Scanner sc = new Scanner(System.in);
 String cricketer = sc.nextLine();
 System.out.println("\n");
 switch (cricketer.toUpperCase()) {
    case "SACHIN":
         System.out.println("You like batting");
         break;
    case "DHONI":
         System.out.println("You like Wicket keeping");
  break;
    case "KUMBLE":
         System.out.println("You like bowling");
                break;
    default:
  System.out.println("You dont like cricket");
 }
  
   }
}


2. Java 7 Try with resources
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. In the below example, the resources declared in the try-with-resources statement are: Connection, Statement and ResultSet from java.sql package. The declaration statement appears within parentheses immediately after the try keyword. The class Connection, Statement and ResultSet, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because these instances are declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method throwing an SQLException). Prior to Java SE 7, you have to use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly.
package com.java7.features;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TryWithResources {
   public static void main(String[] args) throws SQLException {
      try(Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
 Statement stmt = con.createStatement();
 ResultSet rs = stmt.executeQuery("select * from dept")) 
 {
      while(rs.next()) {
      System.out.println("Employee Name : "+rs.getString("deptno"));
      System.out.println("Salary : "+rs.getString("dnmae"));
    }
       };
    }
}
Note: It should be noted that the resources will be closed in the reverse order of their declaration i.e in the above example, first the ResultSet will be closed followed by Statement interface and then finally, the Connection will get closed.

3. Java 7 Multi catch block
In the pre Java 7 world, you would handle exceptions by writing separate catch blocks for different types of exceptions that can occur in the try block. In case of related exception, the derived class exception are listed above the base class exception, e.g. FileNotFoundException should be listed above IOException since FileNotFoundException is derived from the IOException. Java 7 multi catch block provides you the flexibility to combine such catch blocks, provided you have similar code to handle these exceptions and Java 7 provides this by the help of the pipe (|) operator which seperates the different exceptions. Lets have a look at the below example where we handle all the exceptions thrown by the try block in a single catch block, but still specifying the type of exceptions we are handling:
package com.java7.features;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class Java7MultiCatch {
  public static void main(String[] args) {
     try {
       BufferedReader br = new BufferedReader(new FileReader(
          "c:/test.txt"));
       Class.forName("oracle.jdbc.driver.OracleDriver");
       Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1565:myDB");
        } catch (IOException | ClassNotFoundException | SQLException e) {
            System.out.println("Multi catch block here!");
            e.printStackTrace();
        }
 
    }
}

Note: It should be noted that when we use multi catch block, we cannot place the exceptions in a hierarchy seperated by the pipe (|) operator like catch(FileNotFoundException | IOException e) because then the compiler will generate an error that the 'subclass exception (i.e FileNotFoundException) is already caught by an alternative superclass exception (i.e IOException)' which seems to be valid where there is a single exception's stack trace is something we will be dealing with.

Java 7 also introduced new support for File IO operations i.e it introduced Java NIO 2.0 API where the most important concepts are : Path Class and the File Change Notifications using Watch service. I will post it as a seperate entry in the blog soon. Till then, Enjoy reading more about the exciting features of Java 7 :)

Friday, April 29, 2011

Remove Event Listeners

Flex adds event listeners either inline (inside mx tags) or in functions inside script block.
The ways we remove added listeners for the event is same as the way we have added it.
i.e first, we need to call the removeEventListener on that component/container by passing all the parameters
which we passed while calling the addEventListener for the same component/container.
this may be just 2 required parameters as shown below:

comp_id.removeEventListener(eventType:EVENT_TYPE,removeHandlerFunction)

and then finally, we need to define the removeHandlerFunction which expects the same event type that we passed
as EVENT_TYPE in the above method and perform the logic there:

private function removeHandlerFunction(eventType:EVENT_TYPE):void {
....
}

But there is 1 difference in how the event listeners are removed.
If we have added any event listener inline (i.e. inside <mx:> tag for the component or container),
then even calling removeEventListener won't remove it.

However, all the events which are added through addEventListeners (inside script block) can be removed
using the removeEventListener

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" initialize="createHandler(event)">
<mx:Script>
<![CDATA[
import mx.controls.Alert;

private function createHandler(event:Event):void {
b1.addEventListener(MouseEvent.CLICK,myClickHandler);
}

private function removeMyHandlers(event:Event):void {
Alert.show("Removing listener for Button 1");
/* Remove listener for b1's click event because it was added with the addEventListener() method */
b1.removeEventListener(MouseEvent.CLICK,myClickHandler);

/* Does NOT remove the listener for b2's click event because it was added inline i.e in MXML tag */
b2.removeEventListener(MouseEvent.CLICK,myClickHandler);
}

private function myClickHandler(event:Event):void {
Alert.show("The button was clicked");
}
]]>
</mx:Script>

<mx:Button id="b1" label="Click Me (Button 1)" />
<mx:Button id="b2" label="Click Me (Button 2)" click="myClickHandler(event)"/>
<mx:Button id="b3" label="Remove Event Listeners" click="removeMyHandlers(event)"/>
</mx:Application>


In the above example, first try to click button b1. You will see and Alert box saying "The button was clicked". Then, try same for Button b2. You will again see the same output.
Then, try to click the 'Remove Event Listeners' button. This button removes the event listener for b1
since it was added using the addEventListener. But for b2, it does not removes the event listener even though we called the b2.removeEventListener too.

After clicking on the third button, again try to click b1. The alert won't be displayed as it has already removed the listener for this button's click event and hence, it does not call myClickHandler.
However, b2 is still having its listener active and hence its click handler function myClickHandler executes and alert gets displayed on click on b2.

stopPropagation and stopImmediatePropagation

Generally, flex navigates its compelte display list, either upwards towards Application, in Bubbling or Target Phase
or downwards towards the immediate ancestor of the component/container which triggered the event in Capturing Phase.
However, we can stop this navigation or propagation using the following 2 methods of event:

1. stopPropagation: This is used to prevent the Event object from moving onto the next node, but allows the other event listeners (EVENT of same type, example another CLICK) on the current node to execute.
2. stopImmediatePropagation: This is used to prevent the Event object not only to move to next node, but it also does not allow the other event listeners (ONLY OF SAME TYPE, example another CLICK) on the current node to execute

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
click="clickHandler(event)" name="Application" initialize="initApp()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;

private function initApp():void {
myBtn1.addEventListener(MouseEvent.CLICK,anotherClickHandlerForBtn1);
myBtn1.addEventListener(MouseEvent.CLICK,clickHandler);
myBtn1.addEventListener(MouseEvent.ROLL_OUT,rollOutHandler);
myBtn2.addEventListener(MouseEvent.CLICK,anotherClickHandlerForBtn2);
myBtn2.addEventListener(MouseEvent.CLICK,clickHandler);
myBtn2.addEventListener(MouseEvent.ROLL_OUT,rollOutHandler);
}

/*
This will always execute for the buttons
irrespective of stopPropagation or stopImmediatePropagation
as this is a ROLL_OUT event (Event other then CLICK type for which
we are calling the stopPropagation or stopImmediatePropagation)
*/

private function rollOutHandler(event:MouseEvent):void {
Alert.show("Roll Out event for target("+event.target.name+")&"+
" currentTarget("+event.currentTarget.name+")");
}


/*
In this function, we are calling stopPropagation.
So, Flex tries to see if there are any other event other than CLICK on this object or CLICK event itself on parent container. And if there are, it does not execute them
However, if there are more than 1 CLICK handlers for this button itself, it executes all of them. And do not move to the next node in event flow.
*/

private function anotherClickHandlerForBtn1(event:MouseEvent):void {
Alert.show("This is first click handler and would also allow all the other" +
" click handlers of this 'Button 1' to execute (event.stopPropagation)" +
" and stop propagating to other nodes ",event.type);
event.stopPropagation();
}

/*
In this function, we are calling stopImmediatePropagation
So, As soon as this CLICK handler gets executed, Flex stops the event there itself and
no other events gets called (even if there is another CLICK handler, it won't execute)
And also, it does not moves on to the next node in event flow.
*/

private function anotherClickHandlerForBtn2(event:MouseEvent):void {
Alert.show("This will just allow the click handler of this 'Button 2' to execute" +
" and then would stop propagating the event to other click handlers on same node" +
" as well as other nodes (event.stopPropagation)",event.type);
event.stopImmediatePropagation()
}

private function clickHandler(event:MouseEvent):void {
Alert.show("Target object: "+event.target.name
+"\n"+
"Phase: "+getPhaseName(event.eventPhase)
+"\n"+
"Current Target object: "+event.currentTarget.name);
}

private function getPhaseName(phase:uint):String {
switch(phase) {
case 1:
return "CAPTURING PHASE";
case 2:
return "TARGET PHASE";
case 3:
return "BUBBLING PHASE";
}
return "";
}
]]>
</mx:Script>
<mx:Panel borderThickness="250" name="Panel" click="clickHandler(event)" width="700" height="300">
<mx:VBox backgroundColor="#EEEEEE" click="clickHandler(event)" name="VBox" height="200" width="600"
horizontalAlign="center" verticalAlign="middle">
<mx:Label text="Stops propagation to next node but does not stops other events on the same node to execute" />
<mx:Button id="myBtn1" name="Button 1" label="Button 1" />
<mx:Label text="Stops propagation to next node as well as stops other CLICK events on the same node to execute" />
<mx:Button id="myBtn2" name="Button 2" label="Button 2" />
</mx:VBox>
</mx:Panel>
</mx:Application>

Capturing Phase Event

In Flex, we need to know what are the 'target' and 'currentTarget' properties of the Event object and also the
3 stages of Event processing. Let us go through them.

1. target and currentTarget properties: 'target' always refers to the component that has dispatched the event in
first place (example: Button component dispatching click event) and the 'currentTarget' refers to the container
which is currently handling the event (Example, VBOX container in which the above Button is placed and VBOX has
registered for listening to the Button's click event).

In Flex, there are 3 stages of Event processing:
1. Capturing Phase
2. Target Phase
3. Bubbling Phase

Consider the below example which has Application, inside which we have a Panel, inside which we have a VBOox and
then a Button Control.
So, the structure looks like this:

Application
Panel
VBox
Button

Say now, we have clicked on the button. This calls the 'click' event on button. Here, the 'target' object would
always be the same 'button'.

In Capturing Phase: Flex examies the Button's ancestors from the Application right down to the immediate ancestor
of the button (i.e. VBox in this case). This is hardly used. So, in this, the following steps occur during the
capturing phase in same order"
1. Check the Application container for click event listeners (target: Button, currentTarget: Application)
2. Check the Panel container for click event listeners (target: Button, currentTarget: Panel)
3. Check the VBox container for click event listeners (target: Button, currentTarget: VBox)

In Target Phase: Flex reaches the Button for seeing the listeners and here the 'target' and 'currentTarget' refers
to the same component i.e (target:Button, currentTarget: Button)

In Bubbling Phase: Flex examines the Button's ancestors for listeenrs. But here, it starts with the dispatcher's
(button's) immediate ancestor (VBox) and moves all up the display list to the root ancestor (i.e Application). This
is the reverse of the Capturing phase and most often used. The following steps occur in same order:
1. Check the VBox container for click event listeners (target: Button, currentTarget: VBox)
2. Check the Panel container for click event listeners (target: Button, currentTarget: Panel)
3. Check the Application container for click event listeners (target: Button, currentTarget: Application)


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
initialize="addCapturingPhaseEvent(event)" name="Application">
<mx:Script>
<![CDATA[
import mx.controls.Alert;

private function addCapturingPhaseEvent(event:Event):void {
/* to use capturing phase, we need to pass the "useCapture" parameter as true once
and false another time as the third parameter to the addEventListener method.
Passing "false" as the third parameter (Which is by default, but gets overridden if
we have passed as "true" once, will call the Bubbling as well as the Target phase
*/


Application.application.addEventListener(MouseEvent.CLICK,clickHandler,true);

// The below line if commented, will not call the bubbling and the target phase
// as we have set useCapture = true in the previous statement


Application.application.addEventListener(MouseEvent.CLICK,clickHandler,false);
myPanel.addEventListener(MouseEvent.CLICK,clickHandler,true);
myPanel.addEventListener(MouseEvent.CLICK,clickHandler,false);
myBtn.addEventListener(MouseEvent.CLICK,clickHandler,true);
myBtn.addEventListener(MouseEvent.CLICK,clickHandler,false);
myVBox.addEventListener(MouseEvent.CLICK,clickHandler,true);
myVBox.addEventListener(MouseEvent.CLICK,clickHandler,false);
}
private function clickHandler(event:MouseEvent):void {
Alert.show("Target object: "+event.target.name
+"\n"+
"Phase: "+getPhaseName(event.eventPhase)
+"\n"+
"Current Target object: "+event.currentTarget.name);
}

private function getPhaseName(phase:uint):String {
switch(phase) {
case 1:
return "CAPTURING PHASE";
case 2:
return "TARGET PHASE";
case 3:
return "BUBBLING PHASE";
}
return "";
}
]]>
</mx:Script>


<mx:Panel borderThickness="250" name="Panel" id="myPanel" width="500" height="300">
<mx:VBox backgroundColor="#EEEEEE" id="myVBox" name="VBox" height="200" width="300"
horizontalAlign="center" verticalAlign="middle">
<mx:Button name="Button" label="Click Me" id="myBtn" />
</mx:VBox>
</mx:Panel>
</mx:Application>