Skip to content

Commit

Permalink
Reduce finalizer list scanning time
Browse files Browse the repository at this point in the history
  • Loading branch information
wenyuzhao committed Mar 15, 2024
1 parent 7caf8f7 commit bc9669a
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions src/java.base/share/classes/java/lang/ref/Finalizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import jdk.internal.misc.JavaLangAccess;
import jdk.internal.misc.SharedSecrets;
import jdk.internal.misc.VM;
import java.util.ArrayList;

final class Finalizer extends FinalReference<Object> { /* Package-private; must be in
same package as the Reference
Expand All @@ -38,7 +39,8 @@ class */
private static ReferenceQueue<Object> queue = new ReferenceQueue<>();

/** Head of doubly linked list of Finalizers awaiting finalization. */
private static Finalizer unfinalized = null;
private static ArrayList<Finalizer> unfinalized = new ArrayList<>();
private static int unfinalizedCursor = 0;

/** Lock guarding access to unfinalized list. */
private static final Object lock = new Object();
Expand All @@ -49,11 +51,12 @@ private Finalizer(Object finalizee) {
super(finalizee, queue);
// push onto unfinalized
synchronized (lock) {
if (unfinalized != null) {
this.next = unfinalized;
unfinalized.prev = this;
if (unfinalizedCursor < unfinalized.size()) {
unfinalized.set(unfinalizedCursor, this);
} else {
unfinalized.add(this);
}
unfinalized = this;
unfinalizedCursor += 1;
}
}

Expand All @@ -68,17 +71,18 @@ static void register(Object finalizee) {

private void runFinalizer(JavaLangAccess jla) {
synchronized (lock) {
if (this.next == this) // already finalized
int index = -1;
for (int i = 0; i < unfinalizedCursor; i++) {
if (unfinalized.get(i) == this) {
index = i;
break;
}
}
if (index == -1)
return;
// unlink from unfinalized
if (unfinalized == this)
unfinalized = this.next;
else
this.prev.next = this.next;
if (this.next != null)
this.next.prev = this.prev;
this.prev = null;
this.next = this; // mark as finalized
unfinalized.set(index, unfinalized.get(unfinalizedCursor - 1));
unfinalized.set(unfinalizedCursor - 1, null);
unfinalizedCursor -= 1;
}

try {
Expand Down

0 comments on commit bc9669a

Please sign in to comment.