Monday, May 2, 2011

HashMap performance factor:initial capacity and load factor

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, 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 capacity is roughly doubled by calling the rehash method.
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

Implementation of correct hashcode



Scenario:
I have one class Employee That have some filed and Employee also implemented Hash code and equals method
Case 1: Hashcode () was implemented such that it always return some random no for every object.
Like for same object also returning different hascode
Case2: Hashcode () was implemented such way it return same hashcode for all object may me they object are same or different.
What is the output of following program?

public class HascodeTest {
           
            public String name;
           

            public static void main(String[] args) {
                        HashMap test=new HashMap();
                        HascodeTest ht=new HascodeTest("test");
                       
                       
                        test.put(ht,"hello");                 
                        test.put(ht,"hello");
                        test.put(ht,"hello");
                        test.put(ht,"hello");
                        test.put(ht,"hello");
                        System.out.println("HashmapSize"+test.size());
                        System.out.println(ht);
            }


public HascodeTest(String name) {
                        super();                       
                        this.name = name;
            }

            @Override
            public boolean equals(Object obj) {
                        // TODO Auto-generated method stub
                        return super.equals(obj);
                        //return true;
            }



            @Override
            public int hashCode() {
                        // TODO Auto-generated method stub
                        int hashcode=super.hashCode();
                        System.out.println("HashCode:"+hashcode);            
                        int renVal=(int) (31 * Math.random());
                        System.out.println("HashCode"+renVal);
                        return renVal;
                        //return 3  in case 1;
            }


            @Override
            public String toString() {
                        System.out.println("Calling to String ");
                        return this.name;
                       
            }         
}

Ans:
Case 1 :Size of hashmap is 4
Case2:size of hashmap is 1

First it checks if hashode are same then only he goes for equity check and key are equal or not 
i.e if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
So if hashocode are different then it has not check equals.
So implementation of correct hashcode is very important

           
           

static synchronized methods and non-static synchronized method

Q Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.
Q Does a static synchronized method block a non-static synchronized method?
Ans)No As the thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called, these two locks are different and these threads do not block each other.

Thursday, April 28, 2011

Two threads has to print the odd number by one thread and another to print even number



scenario:Say thread t1 and t2 thread objects created.

Thread t1 has to print only the odd number and the t2 has to print the even number.

Solution :

---------------
public class EvenOddGenTest {

/**
* @param args
*/
public static void main(String[] args) {

NumberGenerator numGenerator = new NumberGenerator();

OddGenerator oddGen = new OddGenerator(numGenerator);
EvenGenerator evenGen = new EvenGenerator(numGenerator);

oddGen.start();
evenGen.start();

}

}
------------------

public class OddGenerator extends Thread {

public NumberGenerator numGen;

public OddGenerator(NumberGenerator numberGen) {
this.numGen = numberGen;
}

public void run() {
int i = 1;
while (i <= 9) {

numGen.printOdd(i);
i = i + 2;
}
}

}

----

public class EvenGenerator extends Thread {

public NumberGenerator numGen;

public EvenGenerator(NumberGenerator numberGen) {
this.numGen = numberGen;
}

public void run() {
int i = 2;
while (i <= 10) {
numGen.printEven(i);
i = i + 2;
}
}
}
------


public class NumberGenerator {

boolean oddPrinted = false;

public synchronized void printOdd(int number) {

while (oddPrinted == true) {
try {
wait();

} catch (InterruptedException e) {

}
}

System.out.println("NumberGenerator.printOdd() " + number);
oddPrinted = true;
notifyAll();

}

public synchronized void printEven(int number) {
while (oddPrinted == false) {
try {
wait();

} catch (InterruptedException e) {

}
}

oddPrinted = false;
System.out.println("NumberGenerator.printEven() " + number);
notifyAll();
}
}

--------
Enjoy.... http://www.coderanch.com/images/smilies/e8a506dc4ad763aca51bec4ca7dc8560.gif

puzzles

http://puzzles.nigelcoldwell.co.uk/

A Collection of Quant Riddles With (some) Answers

Wednesday, April 27, 2011

What is the main difference between pass-by-reference and pass-by-value?


What is the main difference between pass-by-reference and pass-by-value?
Ans:
 Other languages use pass-by-reference or pass-by-pointer. But in Java no matter what type of argument you
pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is
exactly how pass-by-value (i.e. copy-by-value) works.
In Java, if a calling method passes a reference of an object as an argument to the called method then the passedin
reference gets copied first and then passed to the called method. Both the original reference that was
passed-in and the copied reference will be pointing to the same object. So no matter which reference you use, you
will be always modifying the same original object, which is how the pass-by-reference works as well.
Add caption
 If your method call involves inter-process (e.g. between two JVMs) communication, then the reference of the
calling method has a different address space to the called method sitting in a separate process (i.e. separate
Java - Fundamentals
41
JVM). Hence inter-process communication involves calling method passing objects as arguments to called method
by-value in a serialized form, which can adversely affect performance due to marshaling and unmarshaling cost.

Tuesday, April 26, 2011

what is the difference between class level lock and object level lock

If a thread T1 enters a method m1 by obtaining the class level lock, does this mean another thread T2 cannot run a different method m2 by obtaining the object level lock?
Ans:


No, it doesn't mean that. The "class level lock" is just a regular lock on a different object, namely SomeClass.class. The "object level lock" locks on this.
Just to make sure I'm following your understanding of the terminology, you're wondering if m1 and m2 can be run concurrently as they are defined below:
public class SomeClass {
    public synchronized static void m1() {
       //do something
    }

    public synchronized void m2() {
       //do something
    }
}
And the answer is yes, m1 and m2 can be run concurrently. It is functionally equivalent to this:
public class SomeClass {
    public static void m1() {
        synchronized (SomeClass.class) {
           //do something
        }
    }
    public void m2() {
        synchronized (this) {
           //do something
        }
    }
}
Since they are synchronizing on completely different objects, they are not mutually exclusive.