Monday, August 31, 2015

performance issue in singleton

if you synchronize out every method call will take time instead if u put inside once the object is instantiated it will never enter syncronzie block unless u null it
public static ASingleton getInstance(){
       if(instance==null){
           synchronized (mutex){
               if(instance==null) instance= new ASingleton();
           }
       }
       return instance;
   }


Fetch the record from employee, department, salary (min/max)

select e.FIRST_NAME, d.DEPT_NAME, min(s.salary), max(s.salary)
from EMPLOYEE e
INNER JOIN DEPARTMENT d  
on e.ID = d.EMP_ID
INNER JOIN SALARY s
on e.ID = s.EMP_ID
WHERE e.ID = '1' GROUP BY e.FIRST_NAME, d.DEPT_NAME;

with out group by na “not a single-group group function” while using min, max

How Hash Map Works In Java Or How Get() Method Works Internally

HashMap works on the principle of Hashing .  To understand Hashing , we should understand the three terms first   i.e  Hash Function , Hash Value and Bucket .

What is Hash Function , Hash Value  and Bucket ?

hashCode() function  which returns an integer value is the Hash function. The important point to note that ,  this method is present in Object class ( Mother of all class ) .

This is the code for the hash function(also known as hashCode method) in Object Class :

    public native int hashCode();


The most important point to note from the above line :  hashCode method return  int value .
So the Hash value is the int value returned by the hash function .


    So summarize the terms in the diagram below :
                   



how hash  map works in java










What is bucket ? 
A bucket is used to store key value pairs . A bucket can have multiple key-value pairs . In hash map, bucket used simple linked list to store objects .



After understanding the terms we are ready to move next step , How hash map works in java or How get() works internally in java .


Code inside Java Api (HashMap class internal implementation) for HashMap get(Obejct key) method 


1.  Public  V get(Object key)
   {
2.     if (key ==null)
3.     //Some code
    
4.     int hash = hash(key.hashCode());
    
5.     // if key found in hash table then  return value
6.     //    else return null
   }

Hash map works on the principle of hashing 

HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of  Entry object . So thinking that Only value is stored  in the bucket is not correct and will not give a good impression on the interviewer .

* Whenever we call get( Key k )  method on the HashMap object . First it checks that whether key is null or not .  Note that there can only be one null key in HashMap .  

If key is null , then Null keys always map to hash 0, thus index 0.

If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode()  ,so after key.hashCode() returns hashValue , line 4 looks like

4.                int hash = hash(hashValue)

 , and now ,it applies returned hashValue into its own hashing function .

We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is ,It defends against poor quality hash functions.

Now step 4 final  hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex) .  

Interviewer:    What if  when two different keys have the same hashcode ?

Solution, equals() method comes to rescue.Here candidate gets puzzled. Since bucket is one and we have two objects with the same hashcode .Candidate usually forgets that bucket is a simple linked list.

The bucket is the linked list effectively . Its not a LinkedList as in a java.util.LinkedList - It's a separate (simpler) implementation just for the map .

So we traverse through linked list , comparing keys in each entries using keys.equals() until it return true.  Then the corresponding entry object Value is returned .



how hashmap works internally in java







One of  our readers Jammy  asked a very good  question 

When the functions 'equals' traverses through the linked list does it traverses from start to end one by one...in other words brute method. Or the linked list is sorted based on key and then it traverses? 

Answer is when an element is added/retrieved, same procedure follows:

 
a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key

b. Pass intial hashvalue as hashValue  in    hash(hashValue) function, to calculate the final hashvalue.

c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method .
    The second parameter is length which is a constant in HashMap Java Api , represented by                             DEFAULT_INITIAL_CAPACITY

    The default  value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api .

 indexFor(int,int) method  returns the first entry in the appropriate bucket. The linked list in the bucket is then iterated over - (the end is found and the element is added or the key is matched and the value is returned )


Explanation about indexFor(int,int) is below :


/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
    return h & (length-1);
}


The above function indexFor() works because Java HashMaps always have a capacity, i.e. number of buckets, as a power of 2.
 Let's work with a capacity of 256,which is 0x100, but it could work with any power of 2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to get the proper bucket index, of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of 1.



Interviewer:    What if  when two  keys are same and have the same hashcode ?
If key needs to be inserted and already inserted hashkey's hashcodes are same, and keys are also same(via reference or using equals() method)  then override the previous key value pair with the current key value pair.

The other important point to note is that in Map ,Any class(String etc.) can serve as a key if and only if it overrides the equals() and hashCode() method .



Interviewer:  How will you measure the performance of HashMap?

According to Oracle Java docs,  

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. 

The capacity is the number of buckets in the hash table( HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.), and the initial capacity is simply the capacity at the time the hash table is created. 


The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

In HashMap class, the default value of load factor is (.75) .

Interviewer : What is the time complexity of Hashmap get() and put() method ?

The hashmap implementation provides constant time performance for (get and put) basic operations
i.e the complexity of get() and put() is O(1) , assuming the hash function disperses the elements properly among the buckets. 

Interviewer : What is the difference between HashMap and ConcurrentHashMap ?

It is also one of the popular interview question on HashMap , you can find the answer here 
HashMap vs ConcurrentHashMap 

why set will not allow duplicate?

PRESENT is just a dummy value -- the set doesn't really care what it is. What the set does care about is the map's keys. So the logic goes like this:
Set.add(a): map.put(a, PRESENT) // so far, this is just what you said the key "a" is in the map, so... keep the "a" key, but map its value to the PRESENT we just passed in also, return the old value (which we'll call OLD) look at the return value: it's OLD, != null. So return false.
Now, the fact that OLD == PRESENT doesn't matter -- and note that Map.put doesn't change the key, just the value mapped to that key. Since the map's keys are what the Set really cares about, the Set is unchanged.


In fact, there has been some change to the underlying structures of the Set -- it replaced a mapping of (a, OLD) with (a, PRESENT). But that's not observable from outside the Set's implementation. (And as it happens, that change isn't even a real change, since OLD == PRESENT).

Wednesday, October 15, 2014

Angular URL search

======================Angular URL search ==========

$scope.getParameterByName = function(namesearch) {
var name = namesearch.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex
.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};

if($scope.getParameterByName('src') )
{
alert($scope.getParameterByName('src'));
}
else if($scope.getParameterByName('cat') )
{
alert($scope.getParameterByName('cat'));
}
else if($scope.getParameterByName('type') )
{
alert($scope.getParameterByName('cat'));
}
else
{
alert("default");
}

Wednesday, December 4, 2013

Setting up SVN version control with FlexBuilder

Setting up SVN version control with FlexBuilder


Jump to: navigation, search
This page discusses the integration of Subversion into FlexBuilder.

Installing Subclipse

The following are instructions for setting up Subversion for Adobe Flex Builder 3 (taken from [1] and [2]). It was last verified on 2009-03-10 to work ok:
Open Flex Builder and do the following:
  1. Help menu → Software Updates → Find and Install → Search for New Features to Install → Check Europa Discovery Site (do not check automatically select mirrors) → Finish
  2. Select a mirror from the List that appeared → Ok
  3. In the new list expand Europa Discovery Site → expand Java Development → select Plug-in Development Enviroment and Java Development Tools → Next → Accept the terms and conditions → Next → Finish
  4. Restart Flex Builder
  5. Help menu → Software Updates → Find and Install → Search for New Features to Install → Button: New Remote Site → Enter the following: name: Subclipse, URL: http://subclipse.tigris.org/update_1.0.x/
  6. Then a new entry should appear in the list with the list with sites for search → Expand Subclipse → Expand Subclipse Plug-in → Check Subclipse 1.2.x (available version might be different when you read this) → Next → Accept the terms and conditions → Next → Finish
  7. Restart Flex Builder
If you encounter a bug using Subclipse: The symptoms are a crash of Flexbuilder on Windows as soon as you want to use it. Subversion uses a library called APR (Apache Portable Runtime) which has a component called APR-ICONV used for translating characters in path and file names to/from UTF-8. The release of Apache 2.2 brought new releases of APR and APR-ICONV and these are not binary compatible with previous releases. Subclipse ships with the Apache 2.0 version of these libraries. The crash occurs if you install an application that installs the Apache 2.2 version of these libraries AND ALSO sets the APR_ICONV_PATH environment variable to a path that contains the Apache 2.2 version of the APR-ICONV .so objects. — Fix: Change the name of the environment variable to APR_ICONV1_PATH. The Apache 2.2 library will look for this environment variable name first, and only fallback to the older name if it is not found. You can safely have an APR_ICONV_PATH environment variable pointing to the Apache 2.0 version of these libraries and the APR_ICONV1_PATH environment variable pointing to the Apache 2.2 version.
Subversion 1.5 has resolved this problem by discontinuing the use of APR-ICONV. Instead, Subversion will use translation routines that are provided by the Windows operating system.

Getting the source code from the SVN repository

We use a subversion repository at sourceforge, see IBIS-ID SourceForge repository for the checkout address. Once you have access you can check out the source code. Here are some instructions that are copied from Flexbuilders manual:

Import a new Project into a SVN Repository

Overview This is the process for taking a local project in your Eclipse workspace and importing it into a repository so that it can be managed by SVN. If you have already been using SVN and you have an existing working copy in your workspace that you want to connect to SVN, then you will likely want to follow the procedure for Connecting an Existing Project.
Procedure If you do not yet have your project ready to import into the repository, create a simple project that contains a few files so that they can be stored in the repository. A simple way to achieve this is to create a sample plug-in project by selecting File > New > Project... and Plug-in Development > Plug-in Project. Give the project a name and click through to finish on the wizard.
To import a project into the repository, right click the project you want to import and select Team > Share Project... from the context menu. Do not use "import" and select subversion.

Shareproject.png

This will begin the Share Project wizard. Select SVN as the repository type and click Next.

Share project svn repository.png

If you have already defined the repository location you want to store this project in, then select it in the list and click Next. Otherwise, select the Create a new repository location option and click Next. If you need to create a location then see the section on creating a new repository location in the Flexbuilder user manual for more information.

Share project folder name.png

You must specify the folder name where you want to store the project. The folder name is relative to the URL of the repository location you specified in the previous step. All intermediate folders must already exist in the repository, but the final folder name must not already exist. You can use the Browse... button to select a path from within the repository. The Browse dialog also allows you to create folders, so you could use that option to create any intermediate folders. In the above example, we are going to follow the convention of storing the project in a ProjectName/trunk structure. In this example, the ProjectName folder must already exist and the trunk folder must not exist. Click Next or Finish when you are through.

Share project ready.png

The final page of the wizard is just a final confirmation page. When you click Finish, SVN will issue the mkdir command to create an empty folder in the repository. It will then checkout that folder on top of your local project. This will create the .svn folder inside your project, converting it into a valid Working Copy. Finally, the wizard will bring up the Commit Dialog so that you can commit everything into the repository. You do not have to commit everything or even anything. You may want to cancel the commit dialog and then go back to your workspace and do everything from the Team menu. For example, if you wanted to set SVN properties as part of the commit, you would want to first use the Team > Add to Version Control option and then use the Team > Set Property option etc. Once you have things the way you want them you can then perform a Team > Commit.
For more and the most up to date details on how to do this please refer to the FlexBuilder online help and go to: Workbench User Guide > Getting started > Team SVN tutorial