想知道某個物件到底被建了幾個?把計數宣告成 static 就是了。原因很單純:類別的靜態變數只會被初始化一次,不管你 new 出多少個實體,那個變數永遠只有一份,天然適合當全域計數器。
下面這個例子示範如何用計數去追蹤「仍在被使用的共享物件」數量,同時順手示範 final 的用法。
package com.glacier.demo;
class Shared {
private int refcount = 0;
private long counter = 0;
private final long id = counter++;
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 Demo {
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) };
for (Composing c : composing) {
c.dispose();
}
}
}
static long counter 負責記錄已建立的物件編號,並為 id 提供遞增數值。這裡刻意選 long 而非 int,是為了在物件數量極大時避免溢位;而 id 加上 final,是因為我們不希望它在整個生命週期裡被改動。
把共享物件掛到某個類別上時,記得呼叫 addRef();等到 dispose() 被觸發,再由引用計數決定何時真正清理。這套技巧很實用,但需要加倍細心,漏掉的 addRef 或 dispose 都會讓計數失準。
執行結果:
Creating Shared 0
Creating Composing 0
Creating Composing 1
Creating Composing 2
Creating Composing 3
Creating Composing 4
disposing Composing 0
disposing Composing 1
disposing Composing 2
disposing Composing 3
disposing Composing 4