Skip to content

Commit

Permalink
Use a process-wide counter instead of identity hash code for phantom …
Browse files Browse the repository at this point in the history
…references in the precise leak detector

The added int field hides in alignment padding on most JVM configurations, so the objects won't actually take up more space from this added field.
  • Loading branch information
chrisvest committed Jul 18, 2024
1 parent 330ffd9 commit 161c60a
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/main/java/stormpot/internal/PreciseLeakDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

public final class PreciseLeakDetector {
Expand All @@ -30,11 +31,11 @@ public final class PreciseLeakDetector {
public PreciseLeakDetector() {
referenceQueue = new ReferenceQueue<>();
leakedObjectCount = new LongAdder();
refs = new IdentityHashSet();
refs = new CountedPhantomRefHashSet();
}

public void register(BSlot<?> slot) {
PhantomReference<Object> ref = new PhantomReference<>(slot.obj, referenceQueue);
CountedPhantomRef<Object> ref = new CountedPhantomRef<>(slot.obj, referenceQueue);
slot.leakCheck = ref;
synchronized (refs) {
refs.add(ref);
Expand Down Expand Up @@ -74,4 +75,22 @@ public long countLeakedObjects() {
accumulateLeaks();
return leakedObjectCount.sum();
}

private static final class CountedPhantomRef<T> extends PhantomReference<T> {
private static final AtomicInteger COUNTER = new AtomicInteger();

private final int id; // This hides in alignment padding on most JVMs, including Lilliput.

CountedPhantomRef(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
id = COUNTER.getAndIncrement();
}
}

private static final class CountedPhantomRefHashSet extends IdentityHashSet {
@Override
protected int hashOf(Object obj) {
return ((CountedPhantomRef<?>) obj).id;
}
}
}

0 comments on commit 161c60a

Please sign in to comment.