Thinking in java 25 引用计数RefCounting

1. 示例代码

package com.fqyuan.thinking;

class Shared {
    // Count of a given class instance used in total.
    private int refcount = 0;
    // Determine the count of instances of this class. 因为是static,所以整个类只有一份。
    private static long count = 0;
    // Flag a given class instance. 因为在类被使用之前被调用,所以会默认每次new一个新对象时+1.
    private final long id = count++;

    public Shared() {
        System.out.println("Creating " + this);
    }

    public void addRef() {
        refcount++;
    }

    protected void dispose() {
        if (--refcount == 0)
            System.out.println("Disposing " + this);
    }

    public String toString() {
        return "Shared " + id;
    }
}

class Composing {
    private Shared shared;
    private static long counter = 0;
    private final long id = counter++;

    public Composing(Shared shared) {
        System.out.println("Creating " + this);
        this.shared = shared;
        this.shared.addRef();
    }

    protected void dispose() {
        System.out.println("Disposing " + this);
        shared.dispose();
    }

    public String toString() {
        return "Composing " + id;
    }

}

public class ReferencingCounting {

    public static void main(String[] args) {
        Shared shared = new Shared();
        Composing[] composing = { new Composing(shared), new Composing(shared), new Composing(shared),
                new Composing(shared), new Composing(shared), new Composing(shared) };
        for (Composing c : composing)
            c.dispose();
    }

}
//Running result:
Creating Shared 0
Creating Composing 0
Creating Composing 1
Creating Composing 2
Creating Composing 3
Creating Composing 4
Creating Composing 5
Disposing Composing 0
Disposing Composing 1
Disposing Composing 2
Disposing Composing 3
Disposing Composing 4
Disposing Composing 5
Disposing Shared 0

2. 代码解释

  • 在Shared对象中有三个成员变量:refcount, count, id.
  • 其中refcount为private int 类型的,代表了给定该Shared类的某个具体对象被使用的次数。在每次使用某个给定的实例后,主动调用addRef()方法完成引用数值的增加。
  • count为private static long类型的,表明该类被用来new对象的总次数,因为是static 类型的,表明该成员变量为该类所共用。它的改变会随着每次new对象时增加。
  • id为private final long类型的,是用来生成新对象标识的机制。通过使用id = count++实现了id的更新,同时更新了count的值。
    因为这些变量都是类成员变量,所以在类创建时就会自动初始化。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值