java.lang.ref
考えられる解決策の 1 つは、ガベージ コレクターとの限られた程度の対話のみをサポートするパッケージに依存することです。
オブジェクトの本当の結末を知ることは難しいため、測定結果は正確ではありませんでした。ジョシュアは時間を測定する別のアプローチを持っているに違いないと私は信じています.JVM自体に向かうかもしれません.
PhantomReference
オブジェクトのライフサイクルの終わりに最も近い参照。つまり、オブジェクトはファントム リーチ可能です。
public class WithoutFinalizationV1 {
public static void main(String[] args) {
ReferenceQueue<WithoutFinalizationV1> queue = new ReferenceQueue<>();
long start = System.nanoTime();
PhantomReference<WithoutFinalizationV1> rf = new PhantomReference<>(
new WithoutFinalizationV1(), queue);
System.gc(); //advise JVM to do GC
Object x = null;
int waitCount = -1;
do{
x = queue.poll();
waitCount++;
} while(x == null);
//only need this time point
System.out.println("WithoutV1 "+ waitCount + " " + (System.nanoTime() - start));
}
}
数回実行すると、世界記録は 5394860ns で、5.6ns には程遠いものです。
追加後
@Override
protected void finalize() throws Throwable {
}
結果は 5632208ns です。
これは私が書いた関連記事からの抜粋です。