• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from Examsimulator

 
GopiKrishnan Chelliah
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It prints infinite loop. i don't know why it calls finalize method? please explain.
class Box{
private int iVolume;
Box(int iVolume){
this.iVolume=iVolume;
}
public void finalize(){
System.out.println("finalizing a Box");
}
}

public class EdGrundy{
boolean stop = false;
public static void main(String argv[]){
new EdGrundy();
}
EdGrundy(){
while(stop==false){
new Box(99);
}
}
}
 
ishmayel vemuru
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi GopiKrishnan Chelliah..
Thi objects of the box Class are not using any where.
If any of the ( BOX ) object is not in use JVM will distroy that( BOX ) objet. Before destroy that type of objects( Un used object) the JVM will cal the finalize method in the corresponding object class if available (finalize method).
Thats why you are getting the out put like..
finalizing a Box
finalizing a Box
finalizing a Box
finalizing a Box
finalizing a Box
finalizing a Box
finalizing a Box
finalizing a Box
finalizing a Box
....
.
.
etc.
I hope you under stand this.
Havae a nice day.
---
Ishmayel
 
Marcus Green
arch rival
Rancher
Posts: 2813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you understand the circumstances under which finalize gets called (This question comes from my web site, any other Archers fans out there?)
 
ishmayel vemuru
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marcus Green....
I didn't get your point..
Do you understand the circumstances under which finalize gets called
Havae a nice day..
----
Ishmayel.
 
Thirugnanam Saravanan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK Let me confirm my understanding with finalize() method.

1. finalize() method will be called by Garbage collector before Garbage Collecting.

2. Normally it should be overridden to clean-up non-Java resources used in a Java Code.

3. finalize() is never run more than once on any object.

4. Since we can't rely on Garbage Collection in Java, we can't assure that finalize() method will always be invoked. Hence we should not have any important business logic inside finalize() method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic