日期:2014-05-20  浏览次数:20798 次

finalize与gc问题
class   Chair  
{
public   static   long   created   =   0;
public   static   long   finalized   =   0;
public   static   boolean   gcrun   =   false;
public   static   boolean   f   =   false;
public   long   i   =   0;

Chair(){
i   =   ++created;
if   (i   ==   1)
{
System.out.println( "Creating   start! ");
}
//System.out.print( ". ");

}

public   void   finalize(){
finalized++;
//System.out.print( "- ");

if   (!gcrun)
{
gcrun   =   true;
System.out.println( "Finalized   start! ");
}
if   (i   ==   47)
{
f   =   true;
System.out.println( "finalized   47   chair, "+created+ "   created,stop   create! ");
}

if   (finalized   > =   created)
{
System.out.println( "All   chair   is   finalized! ");
}
}
}

public   class   Gc
{
public   static   void   main(String   args[]){
while(Chair.f   ==   false){
new   Chair();
new   String( "take   a   few   space ");
}
System.out.println(Chair.created+ "   chair   created, "+Chair.finalized+ "   chair   finalized! ");
System.out.println( "Bye ");
}
}

1.看了think   in   java中关于gc和finalize的介绍,根据书上的例子写了这个程序,但是发现All   chair   is   finalized一直在打印出来,就是说一直在调用finalize,这让我很不解,哪位帮我看看,是什么原因

2.我如果把注解的部分打开,有可以得到正常结果,非常奇怪.

JDK是1.4.2

先谢谢大家了.


------解决方案--------------------
System.out.print();是拖延时间用的.
print()方法相对比较耗时间.

不过在我机器上,如果把两个print方法都注释掉的话,程序有一定几率会出正确结果,其他情况会导致程序一直运行下去,没出现像你说的那样All chair is finalized.
------解决方案--------------------
up
finalize是不定期调用的。
------解决方案--------------------
那你有看到书上类似于这样的一句话吧?“你永远不会知道JVM会在什么时候启动GC”
------解决方案--------------------
可能还有其它的对象(在你的程序没有看到的)也在被回收呢
------解决方案--------------------
< <Effective Java> > 中提到过,不要信赖finalize,因为即使你为你的类编写了这个方法,对消销毁的时候不一定会调用它。所以很多依赖它来释放资源的程序,往往会造成内存溢出
------解决方案--------------------
第二章的第六项:Finalizers are unpredictable, often dangerous, and generally unnecessary.

Effective Java: Programming Language Guide =>

Chapter 2 =>

Item 6: Avoid finalizers

Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, which we 'll cover later in this item, but as a rule of thumb, finalizers should be avoided.