Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

8324972: (bf) Make DirectByteBuffer.Deallocator idempotent #17647

Closed
wants to merge 5 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions src/java.base/share/classes/java/nio/Direct-X-Buffer.java.template
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ import java.io.FileDescriptor;
import java.lang.foreign.MemorySegment;
import java.lang.ref.Reference;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import jdk.internal.foreign.MemorySessionImpl;
import jdk.internal.misc.ScopedMemoryAccess.ScopedAccessError;
import jdk.internal.misc.VM;
@@ -76,19 +76,32 @@ class Direct$Type$Buffer$RW$$BO$

#if[byte]

private record Deallocator(long address, long size, int capacity, AtomicBoolean invoked) implements Runnable {
private static final class Deallocator implements Runnable {

private Deallocator {
private static final AtomicIntegerFieldUpdater<Deallocator> UPDATER =
AtomicIntegerFieldUpdater.newUpdater(Deallocator.class, "invoked");

private final long address;
private final long size;
private final int capacity;
private volatile int invoked;

private Deallocator(long address, long size, int capacity) {
assert address != 0;
this.address = address;
this.size = size;
this.capacity = capacity;
this.invoked = 0;
}

public void run() {
// Ensure idempotency (paranoia)
if (invoked.compareAndSet(false, true)) {
if (UPDATER.compareAndSet(this, 0, 1)) {
UNSAFE.freeMemory(address);
Bits.unreserveMemory(size, capacity);
}
}

}

private final Cleaner cleaner;
@@ -130,7 +143,7 @@ class Direct$Type$Buffer$RW$$BO$
address = base;
}
try {
cleaner = Cleaner.create(this, new Deallocator(base, size, cap, new AtomicBoolean()));
cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
} catch (Throwable t) {
// Prevent leak if the Deallocator or Cleaner fail for any reason
UNSAFE.freeMemory(base);