BAEL-4477 Add a class to demonstrate that the app will crash if too many objects have a finalizer (#10200)

This commit is contained in:
nguyennamthai 2020-10-28 13:12:52 +07:00 committed by GitHub
parent 023d307f51
commit 4b1a853871
1 changed files with 28 additions and 0 deletions

View File

@ -0,0 +1,28 @@
package com.baeldung.finalize;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.Field;
public class CrashedFinalizable {
public static void main(String[] args) throws ReflectiveOperationException {
for (int i = 0; ; i++) {
new CrashedFinalizable();
if ((i % 1_000_000) == 0) {
Class<?> finalizerClass = Class.forName("java.lang.ref.Finalizer");
Field queueStaticField = finalizerClass.getDeclaredField("queue");
queueStaticField.setAccessible(true);
ReferenceQueue<Object> referenceQueue = (ReferenceQueue) queueStaticField.get(null);
Field queueLengthField = ReferenceQueue.class.getDeclaredField("queueLength");
queueLengthField.setAccessible(true);
long queueLength = (long) queueLengthField.get(referenceQueue);
System.out.format("There are %d references in the queue%n", queueLength);
}
}
}
@Override
protected void finalize() {
System.out.print("");
}
}