Thinking in java 25 引用计数RefCounting

来源:互联网 发布:淘宝店铺销量怎么看 编辑:程序博客网 时间:2024/06/14 23:39

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 0Creating Composing 0Creating Composing 1Creating Composing 2Creating Composing 3Creating Composing 4Creating Composing 5Disposing Composing 0Disposing Composing 1Disposing Composing 2Disposing Composing 3Disposing Composing 4Disposing Composing 5Disposing 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的值。
    因为这些变量都是类成员变量,所以在类创建时就会自动初始化。
原创粉丝点击