Tuesday, 18 May 2010
Friday, 18 April 2008
Memory Managment
These are my own views. If it does not match with any texts or if they are different I am not a person to be blamed. Use it on your own risk. ;-)
Last week one of my friends asked me 4 very good questions on GC. So I replied him and part of that i am putting here.
Java has a powerful mechanism known as garbage collection. When object goes out of reference/scope it becomes eligible for garbage collection.
The time garbage collector runs the objects eligible garbage collections are removed from the heap i.e. when object is destroyed its memory is freed and its added as free space in the garbage collector heap's free space.
Implentation Garbage collector can be done using several algorithms one of them is ref. counting.
Java does not provide destructors to stop memory leaks. But it provides finalize method. You can say its a kind of a destructor. When ever any object is destroyed from the heap JVM searches for finalize method if object has finalize method it runs it. Generally its used to free database connections and other shared resources.Actually its safe to forget about the object instead of writting finalize method because finalize method written wrongly will stop GC to collect the object and it will be dangling on the heap. (in case you are having the ref to some other object some other object is not eligible for the GCollection.)
Overhead in terms of if GC finds finalize it runs it and adds overhead;) so its a good practice not to write finalize method your self until you are very sure of the runtime behaviour of the objects.
And finalize method runs at the most one time in the life of the object's life cycle.
You cannot force garbage collector to run. But you can request it using System.gc() and another method is Runtime.gc() But its not sure if GC will listen to your request. ;-)
Last week one of my friends asked me 4 very good questions on GC. So I replied him and part of that i am putting here.
Java has a powerful mechanism known as garbage collection. When object goes out of reference/scope it becomes eligible for garbage collection.
The time garbage collector runs the objects eligible garbage collections are removed from the heap i.e. when object is destroyed its memory is freed and its added as free space in the garbage collector heap's free space.
Implentation Garbage collector can be done using several algorithms one of them is ref. counting.
Java does not provide destructors to stop memory leaks. But it provides finalize method. You can say its a kind of a destructor. When ever any object is destroyed from the heap JVM searches for finalize method if object has finalize method it runs it. Generally its used to free database connections and other shared resources.Actually its safe to forget about the object instead of writting finalize method because finalize method written wrongly will stop GC to collect the object and it will be dangling on the heap. (in case you are having the ref to some other object some other object is not eligible for the GCollection.)
Overhead in terms of if GC finds finalize it runs it and adds overhead;) so its a good practice not to write finalize method your self until you are very sure of the runtime behaviour of the objects.
And finalize method runs at the most one time in the life of the object's life cycle.
You cannot force garbage collector to run. But you can request it using System.gc() and another method is Runtime.gc() But its not sure if GC will listen to your request. ;-)
Super Sawal (question :D)
Hi today I saw a fantastic question of Static blocks,Initializer block and a constructor block.
see the question :
01: class Bird {
02: {
03: System.out.print("b1 ");
04: }
05:
06: public Bird() {
07: System.out.print("b2 ");
08: }
09: }
10:
11: class Raptor extends Bird {
12: static {
13: System.out.print("r1 ");
14: }
15:
16: public Raptor() {
17: System.out.print("r2 ");
18: }
19:
20: {
21: System.out.print("r3 ");
22: }
23:
24: static {
25: System.out.print("r4 ");
26: }
27: }
28:
29: class Hawk extends Raptor {
30: public static void main(String[] args) {
31: System.out.print("pre ");
32: new Hawk();
33: System.out.println("hawk ");
34: }
35: }
Output is: r1 r4 pre b1 b2 r3 r2 hawk
Think why???
If not scroll down :
Do not worry if you cannot understand it for first time. Copy it paste it in a notepad and run. I even could not understand it for first time.
Do you want easier version??
Yes.....Cool try this one then..
1. public class C extends B {
2. public static void main(String[] args) {
3. }
4. }
5. class B extends A {
6. static {
7. System.out.print("B1 ");
8. }
9. static {
10. System.out.print("B2 ");
11. }
12. }
13. class A {
14. static{
15. System.out.print("A ");
16. }
17. }
Predict the output: A B1 B2
Think why if not read...
When a class is having a Static block,initializer block and a constructor :
- Static blocks run first in order of Parent to Child class sequence.(Only one time when classes are loaded.)
- Initializer bocks run second in order of Parent to Child class sequence.(Every time when object of class is created.
Initializer bocks run do not run when the class is loaded
- constructor execute later in order of Parent to Child class sequence.(Every time when object of class is created.)
see the question :
01: class Bird {
02: {
03: System.out.print("b1 ");
04: }
05:
06: public Bird() {
07: System.out.print("b2 ");
08: }
09: }
10:
11: class Raptor extends Bird {
12: static {
13: System.out.print("r1 ");
14: }
15:
16: public Raptor() {
17: System.out.print("r2 ");
18: }
19:
20: {
21: System.out.print("r3 ");
22: }
23:
24: static {
25: System.out.print("r4 ");
26: }
27: }
28:
29: class Hawk extends Raptor {
30: public static void main(String[] args) {
31: System.out.print("pre ");
32: new Hawk();
33: System.out.println("hawk ");
34: }
35: }
Output is: r1 r4 pre b1 b2 r3 r2 hawk
Think why???
If not scroll down :
Do not worry if you cannot understand it for first time. Copy it paste it in a notepad and run. I even could not understand it for first time.
Do you want easier version??
Yes.....Cool try this one then..
1. public class C extends B {
2. public static void main(String[] args) {
3. }
4. }
5. class B extends A {
6. static {
7. System.out.print("B1 ");
8. }
9. static {
10. System.out.print("B2 ");
11. }
12. }
13. class A {
14. static{
15. System.out.print("A ");
16. }
17. }
Predict the output: A B1 B2
Think why if not read...
When a class is having a Static block,initializer block and a constructor :
- Static blocks run first in order of Parent to Child class sequence.(Only one time when classes are loaded.)
- Initializer bocks run second in order of Parent to Child class sequence.(Every time when object of class is created.
Initializer bocks run do not run when the class is loaded
- constructor execute later in order of Parent to Child class sequence.(Every time when object of class is created.)
Executing code without main method.
Let us look at a cool program. Many times in interview just to check your concepts interviewers like to throw tricky questions one of them is : "Can you write a program without a main method and it should compile and run successfully as well it should not throw main() method not found exception?"
Here goes the answer : It can be done in 2 ways. I know most of you know how to do it by one way I will show you two ways ;-) one of them I learnt today!!
1) Declare main method in a parent class. Extend that class and in subclass not not write a main method. Invoke java ChildClassName and bingo it calls parent class method. Try it once to see the magic.
Simplest code goes here :
Example A)
1: public class Test {
2: public static void main(String[] args) {}
3: }
4:
5: class Test1 extends Test {}
You can execute and run the above code by :
java Test1
(Observe class Test1 is not having main method.)
Liked this one? Want to try a little harder?
Example B)
When you compile and run the following code using
java Test1 what will be output?
01: public class Test {
02: public static void main(String[] args) {
03: System.out.println("void");
04: }
05: }
06:
07: class Test1 extends Test {
08: private static void main(String args) {
09: System.out.println("int");
10: }
11: }
Answer:
Compiles and runs fine printing: void
Think why?
Reason:
In class Test1 we have a main method but it is having different signature.
While compile is interested in public static void main(String[] args) .
Compiler fails to find public static void main(String[] args) so it searches it in the super class and it finds it and so it prints "void".
Liked??
Now lets go to 2nd method How to write code without main method.
2) Another way is by using static blocks. From the static block create the object of that class. And in static block of the class write System.exit(); bigo. You are done.
Note: If you don't write System.exit() it will throw main method not found exception at run time.
Code goes here:
01: public class Test {
02: public Test() {
03: System.out.println("hi");
04: }
05:
06: static {
07: new Test();
08: System.exit(0);
09: }
10: }
This code compiles and runs fine printing:hi
When ever class is loaded its static blocks run first.
And from static block we are creating a new object of the same class.
It will return and exit.
Here goes the answer : It can be done in 2 ways. I know most of you know how to do it by one way I will show you two ways ;-) one of them I learnt today!!
1) Declare main method in a parent class. Extend that class and in subclass not not write a main method. Invoke java ChildClassName and bingo it calls parent class method. Try it once to see the magic.
Simplest code goes here :
Example A)
1: public class Test {
2: public static void main(String[] args) {}
3: }
4:
5: class Test1 extends Test {}
You can execute and run the above code by :
java Test1
(Observe class Test1 is not having main method.)
Liked this one? Want to try a little harder?
Example B)
When you compile and run the following code using
java Test1 what will be output?
01: public class Test {
02: public static void main(String[] args) {
03: System.out.println("void");
04: }
05: }
06:
07: class Test1 extends Test {
08: private static void main(String args) {
09: System.out.println("int");
10: }
11: }
Answer:
Compiles and runs fine printing: void
Think why?
Reason:
In class Test1 we have a main method but it is having different signature.
While compile is interested in public static void main(String[] args) .
Compiler fails to find public static void main(String[] args) so it searches it in the super class and it finds it and so it prints "void".
Liked??
Now lets go to 2nd method How to write code without main method.
2) Another way is by using static blocks. From the static block create the object of that class. And in static block of the class write System.exit(); bigo. You are done.
Note: If you don't write System.exit() it will throw main method not found exception at run time.
Code goes here:
01: public class Test {
02: public Test() {
03: System.out.println("hi");
04: }
05:
06: static {
07: new Test();
08: System.exit(0);
09: }
10: }
This code compiles and runs fine printing:hi
When ever class is loaded its static blocks run first.
And from static block we are creating a new object of the same class.
It will return and exit.
Inserting and searching in a Hashtable.
You will be having good knowledge of Data Structors if you can tell:
Which operation takes more time ? put(key,val) or get(key) ?
Think!!
Most of you will think put operation will take more time. Thinking like during put() operation JVM has to calculate the hashCode() and check for equals method. Again Hashtable does not allow duplicates so it will check that too. I was asked this question and I replied in the same way. But I didn't get the correct answer so I was not satisfied I started poll on 2 communities on JavaGuru they moderator deleted the pole :( And on another Java Community till today I got 46 polls.
get(key); 9 Votes (19%)
put(key,val); 21 Votes (45%)
Both take equal time: 16 Votes (34%)
Well I was quite puzzled by this. So I decided to do some R & D on this so what I did is :
I did for a put operation i got 1200 neno seconds more (When i did for 1000 Strings).
For one operation on String
T(put) = T(get) + 1200 neno Seconds.
When i did it for Integer wrappers i got :
T(get) = T(put) + 500 neno Seconds.
But I could not generalize.
Again I did for my userdefined class object i got almost same time for puttign and getting.
And I got
T(get) nearly = T(put)
Recently I read few things in Kathy Sierra book and another Data Structor book that :
Time taken by both the operations will depend on the hashCode() that is generated.
If hashCode is poor then get() operation will take time as the search will become almost sequential.
Both need to find the "bucket" that is appropriate for the hash of the key.
If the hash code was poor, the put would take less time as the get would have to do a linear search through the whole bucket.
But Hashtable generates 'decent code' and not poor code.
Which operation takes more time ? put(key,val) or get(key) ?
Think!!
Most of you will think put operation will take more time. Thinking like during put() operation JVM has to calculate the hashCode() and check for equals method. Again Hashtable does not allow duplicates so it will check that too. I was asked this question and I replied in the same way. But I didn't get the correct answer so I was not satisfied I started poll on 2 communities on JavaGuru they moderator deleted the pole :( And on another Java Community till today I got 46 polls.
get(key); 9 Votes (19%)
put(key,val); 21 Votes (45%)
Both take equal time: 16 Votes (34%)
Well I was quite puzzled by this. So I decided to do some R & D on this so what I did is :
I did for a put operation i got 1200 neno seconds more (When i did for 1000 Strings).
For one operation on String
T(put) = T(get) + 1200 neno Seconds.
When i did it for Integer wrappers i got :
T(get) = T(put) + 500 neno Seconds.
But I could not generalize.
Again I did for my userdefined class object i got almost same time for puttign and getting.
And I got
T(get) nearly = T(put)
Recently I read few things in Kathy Sierra book and another Data Structor book that :
Time taken by both the operations will depend on the hashCode() that is generated.
If hashCode is poor then get() operation will take time as the search will become almost sequential.
Both need to find the "bucket" that is appropriate for the hash of the key.
If the hash code was poor, the put would take less time as the get would have to do a linear search through the whole bucket.
But Hashtable generates 'decent code' and not poor code.
Equals() and hashCode()
When :
Object1.equals(Object2) = true at that time
Object1.hashCode() == Object2.hashCode()
But when
Object1.hashCode() == Object2.hashCode() its not required that
Object1.equals(Object2) = true.
Very less people know why! Lets unreveal the secret ;-)
Think as if you are a laundry man and you wash clothes for only one person.
Suppose you have 1000 buckets numbered on their body. Number starting from 1 onwards. Now you want to do some searching technique say you have clothes to put in the bucket. You are very smart so you want to employ some algorithm to fasten the search process. So what you do is : You see the cloth, if its Shirt you calculate its numerical value like a =1, b=2 and so on. so calculating the shirt's numerical value gives you "x" so what you do is, you put this shirt in xth bucket. Again you have a cap you want to put it. You find out its numerical value say "y" and you put cap in Yth bucket. Now you wash all the clothes and you are done.
Now your customer comes and asks only for cap. What will you do? will you search that cap in all 1000 buckets? What a loss if you do so!! So what you do is you think cap ok.... let me calculate its value it comes to "y" and you go to yth bucket and search the cap and give it to your customer you are done. This numerical value is nothing but hashCode in a way.
Now think you got 50 customers and you wash for them then? in xth bucket and yth bucket you will have 50 -50 pieces of clothes. God... Now how will you identify that this cap belongs to customer1 or customer2?
Here equals() method comes handy. You will write your own equals() method to compare if this cap is for me or its for you.
Its just an example. The algorithm which I showed you for calculating hashCode() is poor but valid ;-) it was just to explain the concept easily. In big structors we will be having powerful algorithms to calculate hashCodes.
More powerful the hashCode generation algorithm is less time time it takes for search operation. In the worst case it will be linear search (in case of pooer hashcode generating algorithm.)
In the beginning I said when 2 objects are having equal hashCode its not necessary that both objects are equal. Because say you are calculating hashCode on names say two customer names are : May and Amy both will be having same hashCode() their objects will go in same bucket. So both objects are not equal but they are having equal hashCode().
This is the reason while overriding hashCode() we override equals() also;-)
1 more thing secret to share :
Hashtable allows only the objects (as key or value) which objects have equals() and hashCode() methods(if not override these methods should be present in super class).
And this is the reason why Hashtable does not allow null values as key or values.
Object1.equals(Object2) = true at that time
Object1.hashCode() == Object2.hashCode()
But when
Object1.hashCode() == Object2.hashCode() its not required that
Object1.equals(Object2) = true.
Very less people know why! Lets unreveal the secret ;-)
Think as if you are a laundry man and you wash clothes for only one person.
Suppose you have 1000 buckets numbered on their body. Number starting from 1 onwards. Now you want to do some searching technique say you have clothes to put in the bucket. You are very smart so you want to employ some algorithm to fasten the search process. So what you do is : You see the cloth, if its Shirt you calculate its numerical value like a =1, b=2 and so on. so calculating the shirt's numerical value gives you "x" so what you do is, you put this shirt in xth bucket. Again you have a cap you want to put it. You find out its numerical value say "y" and you put cap in Yth bucket. Now you wash all the clothes and you are done.
Now your customer comes and asks only for cap. What will you do? will you search that cap in all 1000 buckets? What a loss if you do so!! So what you do is you think cap ok.... let me calculate its value it comes to "y" and you go to yth bucket and search the cap and give it to your customer you are done. This numerical value is nothing but hashCode in a way.
Now think you got 50 customers and you wash for them then? in xth bucket and yth bucket you will have 50 -50 pieces of clothes. God... Now how will you identify that this cap belongs to customer1 or customer2?
Here equals() method comes handy. You will write your own equals() method to compare if this cap is for me or its for you.
Its just an example. The algorithm which I showed you for calculating hashCode() is poor but valid ;-) it was just to explain the concept easily. In big structors we will be having powerful algorithms to calculate hashCodes.
More powerful the hashCode generation algorithm is less time time it takes for search operation. In the worst case it will be linear search (in case of pooer hashcode generating algorithm.)
In the beginning I said when 2 objects are having equal hashCode its not necessary that both objects are equal. Because say you are calculating hashCode on names say two customer names are : May and Amy both will be having same hashCode() their objects will go in same bucket. So both objects are not equal but they are having equal hashCode().
This is the reason while overriding hashCode() we override equals() also;-)
1 more thing secret to share :
Hashtable allows only the objects (as key or value) which objects have equals() and hashCode() methods(if not override these methods should be present in super class).
And this is the reason why Hashtable does not allow null values as key or values.
Sunday, 6 April 2008
Hello World!
Here I would be sharing some thing about Java and Java EE related concepts as well my learnings.
People can use it at their own risks.
People can use it at their own risks.
Subscribe to:
Comments (Atom)