GC如何知道对象没被引用(孤岛例子)

引用计数方法不好,没有一种虚拟机使用它。

Java 虚拟机启动一个线程从栈和静态储存区开始,遍历所有引用,就可以找到所有还在使用中的对象。至于没有被引用的对象,或者像 3 楼说的那种“孤岛”,不会被遍历到,所以会被回收。

基于这样的理论,有两种实践方法,一种方法暂停当前程序的执行,将所有找到的对象复制到另一块内存区域,没有找到的对象自然就没有复制,这种方法叫“停止-复制”,

另一种方法并不暂停程序,在遍历到对象时给它设个标记,遍历完后回收所有没有标记的对象。这种方法叫“标记-清除”。










验证GC对孤岛的回收:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class  Island{
     public  Island brother;
     String name;
     public  Island(){
     }
     public  Island(String name){
         this .name = name;
     }
     public  void  finalize(){
         System.out.println( this .name +  "对象成为垃圾,被收集" );
     }
     public  void  testIsland(){
         Island i1 =  new  Island( "孤岛中的 O1" );
         Island i2 =  new  Island( "孤岛中的 O2" );
         Island i3 =  new  Island( "孤岛中的 O3" );
         
         i1.brother = i2;
         i2.brother = i3;
         i3.brother = i1;
         
         i1 =  null ;
         i2 =  null ;
         i3 =  null ;
         // 这样 三个对象循环指向  但他们形成了孤岛 所以已经成为垃圾 
         
         System.gc(); //可以看到 三个对象很快被收集,但程序过了10s才结束
         try {
             Thread.sleep( 10000 );
         } catch (Exception e){
             e.printStackTrace();
         }
     }
}
 
public  class  Test{
     public  static  void  main(String[] args){
         new  Island().testIsland();
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值