Skip to content

Commit d0593dc

Browse files
BAEL-4477 Add a class to demonstrate that the app will crash if too many objects have a finalizer (eugenp#10200)
1 parent 2d6524e commit d0593dc

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.finalize;
2+
3+
import java.lang.ref.ReferenceQueue;
4+
import java.lang.reflect.Field;
5+
6+
public class CrashedFinalizable {
7+
public static void main(String[] args) throws ReflectiveOperationException {
8+
for (int i = 0; ; i++) {
9+
new CrashedFinalizable();
10+
if ((i % 1_000_000) == 0) {
11+
Class<?> finalizerClass = Class.forName("java.lang.ref.Finalizer");
12+
Field queueStaticField = finalizerClass.getDeclaredField("queue");
13+
queueStaticField.setAccessible(true);
14+
ReferenceQueue<Object> referenceQueue = (ReferenceQueue) queueStaticField.get(null);
15+
16+
Field queueLengthField = ReferenceQueue.class.getDeclaredField("queueLength");
17+
queueLengthField.setAccessible(true);
18+
long queueLength = (long) queueLengthField.get(referenceQueue);
19+
System.out.format("There are %d references in the queue%n", queueLength);
20+
}
21+
}
22+
}
23+
24+
@Override
25+
protected void finalize() {
26+
System.out.print("");
27+
}
28+
}

0 commit comments

Comments
 (0)