diff --git a/memory/memory-core/src/main/java/org/apache/arrow/memory/BufferLedger.java b/memory/memory-core/src/main/java/org/apache/arrow/memory/BufferLedger.java index eb90efcbb5..e090cb1a9e 100644 --- a/memory/memory-core/src/main/java/org/apache/arrow/memory/BufferLedger.java +++ b/memory/memory-core/src/main/java/org/apache/arrow/memory/BufferLedger.java @@ -174,8 +174,16 @@ public void retain(int increment) { if (historicalLog != null) { historicalLog.recordEvent("retain(%d)", increment); } - final int originalReferenceCount = BUF_REF_CNT_UPDATER.getAndAdd(this, increment); - Preconditions.checkArgument(originalReferenceCount > 0); + int originalReferenceCount; + do { + originalReferenceCount = BUF_REF_CNT_UPDATER.get(this); + // Check before writing. An unconditional add leaves the count positive on a ledger + // that was already released, which lets the next retain() succeed and lets + // ArrowBuf's reference count check pass for memory that has already been freed. + Preconditions.checkArgument( + originalReferenceCount > 0, "retain() on a ledger with no remaining references"); + } while (!BUF_REF_CNT_UPDATER.compareAndSet( + this, originalReferenceCount, originalReferenceCount + increment)); } /** diff --git a/memory/memory-core/src/test/java/org/apache/arrow/memory/TestBaseAllocator.java b/memory/memory-core/src/test/java/org/apache/arrow/memory/TestBaseAllocator.java index 87e9316964..6662cb3ae6 100644 --- a/memory/memory-core/src/test/java/org/apache/arrow/memory/TestBaseAllocator.java +++ b/memory/memory-core/src/test/java/org/apache/arrow/memory/TestBaseAllocator.java @@ -273,6 +273,26 @@ public void testAllocator_shareOwnership() throws Exception { } } + @Test + public void testRetainOnReleasedBufferIsRejectedRepeatedly() throws Exception { + try (final RootAllocator rootAllocator = new RootAllocator(MAX_ALLOCATION)) { + final ArrowBuf arrowBuf = rootAllocator.buffer(512); + final ReferenceManager referenceManager = arrowBuf.getReferenceManager(); + referenceManager.release(); + assertEquals(0, arrowBuf.refCnt()); + + // Each retain on the released ledger has to be rejected, and has to leave the + // reference count at 0 so that ArrowBuf keeps refusing access to the freed memory. + assertThrows(IllegalArgumentException.class, referenceManager::retain); + assertEquals(0, arrowBuf.refCnt()); + assertThrows(IllegalArgumentException.class, referenceManager::retain); + assertEquals(0, arrowBuf.refCnt()); + assertThrows(IllegalArgumentException.class, () -> referenceManager.retain(2)); + assertEquals(0, arrowBuf.refCnt()); + assertThrows(IllegalStateException.class, () -> arrowBuf.setInt(0, 1)); + } + } + @Test public void testRootAllocator_createChildAndUse() throws Exception { try (final RootAllocator rootAllocator = new RootAllocator(MAX_ALLOCATION)) {