GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Fix shared scanForCapacity: LRU preference, livelock prevention, epoc… · netty/netty@ec796ae

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • buffer/src
    • main/java/io/netty/buffer
      • AdaptivePoolingAllocator.java
    • test/java/io/netty/buffer
      • SizeClassedChunkCacheTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java‎

Copy file name to clipboardExpand all lines: buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java
+98-19Lines changed: 98 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ private AdaptiveByteBuf allocate(int size, int maxCapacity, Thread currentThread
247247
if (!FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals() ||
248248
IS_LOW_MEM ||
249249
(magazineGroups = threadLocalGroup.get()) == null) {
250-
magazineGroups = sizeClassedMagazineGroups;
250+
magazineGroups = sizeClassedMagazineGroups;
251251
}
252252
if (index < magazineGroups.length) {
253253
allocated = magazineGroups[index].allocate(size, maxCapacity, currentThread, buf);
@@ -296,7 +296,7 @@ private AdaptiveByteBuf allocateFallback(int size, int maxCapacity, Thread curre
296296
chunkRegistry.add(chunk);
297297
try {
298298
boolean success = chunk.readInitInto(buf, size, size, maxCapacity);
299-
assert success: "Failed to initialize ByteBuf with dedicated chunk";
299+
assert success : "Failed to initialize ByteBuf with dedicated chunk";
300300
} finally {
301301
// As the chunk is an one-off we need to always call release explicitly as readInitInto(...)
302302
// will take care of retain once when successful. Once The AdaptiveByteBuf is released it will
@@ -316,7 +316,7 @@ private Magazine getFallbackMagazine(Thread currentThread) {
316316
*/
317317
void reallocate(int size, int maxCapacity, AdaptiveByteBuf into) {
318318
AdaptiveByteBuf result = allocate(size, maxCapacity, Thread.currentThread(), into);
319-
assert result == into: "Re-allocation created separate buffer instance";
319+
assert result == into : "Re-allocation created separate buffer instance";
320320
}
321321

322322
long usedMemory() {
@@ -503,6 +503,7 @@ private void freeChunkReuseQueue(Thread ownerThread) {
503503

504504
interface ChunkCache {
505505
Chunk pollChunk(int size);
506+
506507
boolean offerChunk(Chunk chunk);
507508
}
508509

@@ -639,13 +640,16 @@ private SizeClassedChunk scanForCapacity() {
639640
if (notEmptyCount > 0) {
640641
SizeClassedChunk chunk = chunks[head];
641642
assert chunk.hasRemainingCapacity();
642-
chunk.purgeEpoch = 0;
643643
chunks[head] = null;
644644
head = (head + 1) & (chunks.length - 1);
645645
count--;
646646
notEmptyCount--;
647647
return chunk;
648648
}
649+
return scanForCapacityFallback();
650+
}
651+
652+
private SizeClassedChunk scanForCapacityFallback() {
649653
int mask = chunks.length - 1;
650654
int pos = (head + notEmptyCount) & mask;
651655
int end = tail;
@@ -710,6 +714,7 @@ private void closeGap(int kept) {
710714

711715
private void partition(int size) {
712716
int mask = chunks.length - 1;
717+
// First pass: hasCapacity to front, noCapacity to back.
713718
int lo = 0;
714719
int hi = size - 1;
715720
while (lo <= hi) {
@@ -725,6 +730,22 @@ private void partition(int size) {
725730
}
726731
}
727732
notEmptyCount = lo;
733+
// Second pass: within the notEmpty zone [head, head+lo),
734+
// sub-partition epoch==0 to front, epoch>0 behind.
735+
int elo = 0;
736+
int ehi = lo - 1;
737+
while (elo <= ehi) {
738+
int eloIdx = (head + elo) & mask;
739+
if (chunks[eloIdx].purgeEpoch == 0) {
740+
elo++;
741+
} else {
742+
int ehiIdx = (head + ehi) & mask;
743+
SizeClassedChunk tmp = chunks[eloIdx];
744+
chunks[eloIdx] = chunks[ehiIdx];
745+
chunks[ehiIdx] = tmp;
746+
ehi--;
747+
}
748+
}
728749
}
729750

730751
@Override
@@ -749,11 +770,11 @@ public String toString() {
749770
int mask = chunks.length - 1;
750771
StringBuilder sb = new StringBuilder();
751772
sb.append("ThreadLocalCache[head=").append(head)
752-
.append(", tail=").append(tail)
753-
.append(", count=").append(count)
754-
.append(", notEmpty=").append(notEmptyCount)
755-
.append(", length=").append(chunks.length)
756-
.append("]\n ");
773+
.append(", tail=").append(tail)
774+
.append(", count=").append(count)
775+
.append(", notEmpty=").append(notEmptyCount)
776+
.append(", length=").append(chunks.length)
777+
.append("]\n ");
757778
for (int i = 0; i < count; i++) {
758779
if (i > 0) {
759780
sb.append(", ");
@@ -766,12 +787,40 @@ public String toString() {
766787
String actual = c == null ? "null" :
767788
c.hasRemainingCapacity() ? "hasCap" : "noCap";
768789
sb.append('[').append(region).append(':').append(actual)
769-
.append(",ep=").append(c == null ? -1 : c.purgeEpoch).append(']');
790+
.append(",ep=").append(c == null ? -1 : c.purgeEpoch).append(']');
770791
}
771792
return sb.toString();
772793
}
773794
}
774795

796+
/**
797+
* MPMC queue cache for shared (cross-thread) chunk reuse.
798+
*
799+
* <p><b>scanForCapacity</b> — LRU preference with fallback:
800+
* <pre>
801+
* fast path: head chunk has purgeEpoch == 0 and capacity → return O(1)
802+
*
803+
* slow path: scan for epoch=0 chunk, hold first idle (epoch &gt; 0) as fallback
804+
* queue: [E&gt;0, E&gt;0, E=0, E&gt;0, ...]
805+
* skip skip ↑ return (put fallback back)
806+
*
807+
* no epoch=0 found → use fallback, reset its epoch to 0
808+
* </pre>
809+
*
810+
* <p>The LRU preference creates a natural separation: recently-used chunks (epoch=0,
811+
* returned via {@link #offerChunk} after magazine use) cycle at the front. Idle chunks
812+
* (epoch &gt; 0, aged by purge) are scanned past but never returned — they age undisturbed.
813+
* When no recently-used chunks exist, idle ones are reused (fallback) rather than
814+
* allocating new chunks.
815+
*
816+
* <p>All re-offered chunks are stamped with {@code lastScanGeneration} for cycle detection.
817+
* The {@code >=} check terminates the scan when encountering any chunk already processed
818+
* by this or a later scan, preventing livelock under concurrent access.
819+
*
820+
* <p><b>runPurgeScan</b> (every {@link #CHUNK_PURGE_POLLS_SHARED} polls):
821+
* drains the queue, ages full chunks (epoch++), resets non-full (epoch=0),
822+
* evicts past threshold while retaining at least {@link #CHUNK_REUSE_QUEUE} chunks.
823+
*/
775824
static final class SharedSizeClassedChunkCache extends SizeClassedChunkCache {
776825
// Must exceed CHUNK_REUSE_QUEUE (the retention floor) to leave room for burst absorption.
777826
// TODO replace with an unbounded concurrent collection once available.
@@ -808,30 +857,57 @@ private SizeClassedChunk scanForCapacity() {
808857
if (first == null) {
809858
return null;
810859
}
811-
if (first.hasRemainingCapacity()) {
860+
if (first.purgeEpoch == 0 && first.hasRemainingCapacity()) {
812861
return first;
813862
}
863+
if (first.hasRemainingCapacity()) {
864+
return scanForCapacitySlow(first);
865+
}
814866
long generation = scanGeneration.incrementAndGet();
815867
first.lastScanGeneration = generation;
816868
if (!queue.offer(first)) {
817869
first.markToDeallocate();
818870
return null;
819871
}
872+
return scanForCapacitySlow(generation, null);
873+
}
874+
875+
private SizeClassedChunk scanForCapacitySlow(SizeClassedChunk fallback) {
876+
long generation = scanGeneration.incrementAndGet();
877+
fallback.lastScanGeneration = generation;
878+
return scanForCapacitySlow(generation, fallback);
879+
}
880+
881+
private SizeClassedChunk scanForCapacitySlow(long generation, SizeClassedChunk fallback) {
820882
SizeClassedChunk chunk;
821883
while ((chunk = queue.poll()) != null) {
822884
if (chunk.lastScanGeneration >= generation) {
823885
if (!queue.offer(chunk)) {
824886
chunk.markToDeallocate();
825887
}
826-
return null;
888+
break;
827889
}
828890
if (chunk.hasRemainingCapacity()) {
829-
return chunk;
891+
if (chunk.purgeEpoch == 0) {
892+
if (fallback != null) {
893+
queue.offer(fallback);
894+
}
895+
return chunk;
896+
}
897+
if (fallback == null) {
898+
fallback = chunk;
899+
continue;
900+
}
830901
}
902+
chunk.lastScanGeneration = generation;
831903
if (!queue.offer(chunk)) {
832904
chunk.markToDeallocate();
833905
}
834906
}
907+
if (fallback != null) {
908+
fallback.purgeEpoch = 0;
909+
return fallback;
910+
}
835911
return null;
836912
}
837913

@@ -1128,9 +1204,11 @@ public Chunk newChunkAllocation(int promptingSize, Magazine magazine) {
11281204

11291205
private static final class Magazine {
11301206
private static final AtomicReferenceFieldUpdater<Magazine, Chunk> NEXT_IN_LINE;
1207+
11311208
static {
11321209
NEXT_IN_LINE = AtomicReferenceFieldUpdater.newUpdater(Magazine.class, Chunk.class, "nextInLine");
11331210
}
1211+
11341212
private static final Chunk MAGAZINE_FREED = new Chunk();
11351213

11361214
private static final class AdaptiveRecycler extends Recycler<AdaptiveByteBuf> {
@@ -1382,7 +1460,7 @@ void free() {
13821460

13831461
public AdaptiveByteBuf newBuffer() {
13841462
AdaptiveRecycler recycler = this.recycler;
1385-
AdaptiveByteBuf buf = recycler == null? EVENT_LOOP_LOCAL_BUFFER_POOL.get() : recycler.get();
1463+
AdaptiveByteBuf buf = recycler == null ? EVENT_LOOP_LOCAL_BUFFER_POOL.get() : recycler.get();
13861464
buf.resetRefCnt();
13871465
buf.discardMarks();
13881466
return buf;
@@ -1449,7 +1527,7 @@ static class Chunk implements ChunkInfo {
14491527
}
14501528
}
14511529

1452-
Magazine currentMagazine() {
1530+
Magazine currentMagazine() {
14531531
return magazine;
14541532
}
14551533

@@ -1489,7 +1567,7 @@ void markToDeallocate() {
14891567
}
14901568

14911569
private void retain() {
1492-
RefCnt.retain(refCnt);
1570+
RefCnt.retain(refCnt);
14931571
}
14941572

14951573
protected boolean release() {
@@ -1620,7 +1698,7 @@ static class SizeClassedChunk extends Chunk {
16201698
// making late-arriving releaseSegment calls on external threads arithmetically harmless.
16211699
private static final int DEALLOCATED = Integer.MIN_VALUE;
16221700
private static final AtomicIntegerFieldUpdater<SizeClassedChunk> STATE =
1623-
AtomicIntegerFieldUpdater.newUpdater(SizeClassedChunk.class, "state");
1701+
AtomicIntegerFieldUpdater.newUpdater(SizeClassedChunk.class, "state");
16241702
private volatile int state;
16251703
private final int segments;
16261704
private final int segmentSize;
@@ -2042,7 +2120,7 @@ public ByteBuf capacity(int newCapacity) {
20422120
allocator.reallocate(newCapacity, maxCapacity(), this);
20432121
oldRoot.getBytes(baseOldRootIndex, this, 0, oldLength);
20442122
chunk.releaseSegment(baseOldRootIndex, oldCapacity);
2045-
assert oldCapacity < maxFastCapacity && newCapacity <= maxFastCapacity:
2123+
assert oldCapacity < maxFastCapacity && newCapacity <= maxFastCapacity :
20462124
"Capacity increase failed";
20472125
this.readerIndex = readerIndex;
20482126
this.writerIndex = writerIndex;
@@ -2479,8 +2557,9 @@ protected void deallocate() {
24792557
interface ChunkAllocator {
24802558
/**
24812559
* Allocate a buffer for a chunk. This can be any kind of {@link AbstractByteBuf} implementation.
2560+
*
24822561
* @param initialCapacity The initial capacity of the returned {@link AbstractByteBuf}.
2483-
* @param maxCapacity The maximum capacity of the returned {@link AbstractByteBuf}.
2562+
* @param maxCapacity The maximum capacity of the returned {@link AbstractByteBuf}.
24842563
* @return The buffer that represents the chunk memory.
24852564
*/
24862565
AbstractByteBuf allocate(int initialCapacity, int maxCapacity);
Collapse file

‎buffer/src/test/java/io/netty/buffer/SizeClassedChunkCacheTest.java‎

Copy file name to clipboardExpand all lines: buffer/src/test/java/io/netty/buffer/SizeClassedChunkCacheTest.java
+60-28Lines changed: 60 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -290,45 +290,77 @@ void cacheSettlesAtRetentionFloorAfterBurst(boolean threadLocal) {
290290
assertEquals(floor, retained, "retention floor chunks should survive");
291291
}
292292

293-
// --- stale epoch: chunk polled with accumulated epoch, reused, re-offered (thread-local only) ---
294-
// Thread-local scanForCapacity resets purgeEpoch on poll (ring partitioning isolates idle chunks).
295-
// Shared cache does not reset — FIFO rotation would reset all chunks, preventing aging.
293+
// --- epoch aging: polled chunks carry their epoch (no reset on poll) ---
294+
// Thread-local: partition sub-ordering puts epoch=0 at head, epoch>0 behind.
295+
// Epoch reset on poll would defeat aging when polls > chunks (e.g., 2-core: 16 polls, 7 chunks).
296+
// Shared: LRU preference in scanForCapacity achieves the same without epoch reset.
296297

297-
@Test
298-
void polledChunkWithStaleEpochShouldNotBeEvictedPrematurely() {
299-
SizeClassedChunkCache cache = SizeClassedChunkCache.create(true);
298+
@ParameterizedTest
299+
@ValueSource(booleans = {true, false})
300+
void excessChunksAgeAndEvictDespiteBeingPolled(boolean threadLocal) {
301+
SizeClassedChunkCache cache = SizeClassedChunkCache.create(threadLocal);
300302

301-
// Pad above retention floor
303+
// Pad to retention floor
302304
for (int i = 0; i < AdaptivePoolingAllocator.CHUNK_REUSE_QUEUE; i++) {
303305
cache.offerChunk(chunkWithoutCapacity());
304306
}
305307

306-
// A fully-free chunk that will age
307-
SizeClassedChunk chunk = mock(SizeClassedChunk.class);
308-
when(chunk.remainingCapacity()).thenReturn(4096);
309-
when(chunk.capacity()).thenReturn(4096);
310-
when(chunk.hasRemainingCapacity()).thenReturn(true);
311-
cache.offerChunk(chunk);
308+
// Add excess idle chunks above the floor
309+
int excess = 3;
310+
SizeClassedChunk[] idleChunks = new SizeClassedChunk[excess];
311+
for (int i = 0; i < excess; i++) {
312+
idleChunks[i] = idleChunk();
313+
cache.offerChunk(idleChunks[i]);
314+
}
312315

313-
// Age it to just below threshold via purge cycles
314-
// Each purge: chunk is fully free (remaining==capacity) → epoch++
315-
// It also has capacity, so scanForCapacity (called after purge) will poll it.
316-
// We re-offer it each time to keep it in the cache.
317-
for (int i = 0; i < AdaptivePoolingAllocator.CHUNK_PURGE_THRESHOLD - 1; i++) {
316+
// Run enough purge cycles for excess to age past threshold and be evicted
317+
for (int i = 0; i < AdaptivePoolingAllocator.CHUNK_PURGE_THRESHOLD + 1; i++) {
318318
cache.forcePurge();
319-
cache.offerChunk(chunk);
320319
}
321320

322-
// Chunk has been polled and re-offered each cycle.
323-
SizeClassedChunk polled = cache.forcePurge();
324-
assertNotNull(polled);
325-
assertEquals(0, polled.purgeEpoch);
321+
// All excess should be evicted — cache settles at the retention floor
322+
for (SizeClassedChunk idle : idleChunks) {
323+
verify(idle, atLeastOnce()).markToDeallocate();
324+
}
325+
}
326326

327-
// Re-offer as fully free (simulating: used briefly, all segments returned)
328-
cache.offerChunk(polled);
327+
// --- shared cache: concurrent scanForCapacity must not livelock ---
329328

330-
// One more purge — should NOT evict (epoch was reset on each poll)
331-
cache.forcePurge();
332-
verify(chunk, never()).markToDeallocate();
329+
@Test
330+
void concurrentScansTerminateWhenNoCapacity() throws Exception {
331+
SizeClassedChunkCache cache = SizeClassedChunkCache.create(false);
332+
333+
// Fill with no-capacity chunks — no scan can find anything
334+
for (int i = 0; i < 10; i++) {
335+
cache.offerChunk(chunkWithoutCapacity());
336+
}
337+
338+
int threadCount = 4;
339+
java.util.concurrent.CountDownLatch startLatch = new java.util.concurrent.CountDownLatch(1);
340+
java.util.concurrent.CountDownLatch doneLatch = new java.util.concurrent.CountDownLatch(threadCount);
341+
java.util.concurrent.atomic.AtomicReference<Throwable> error =
342+
new java.util.concurrent.atomic.AtomicReference<>();
343+
344+
for (int t = 0; t < threadCount; t++) {
345+
new Thread(() -> {
346+
try {
347+
startLatch.await();
348+
for (int i = 0; i < 1000; i++) {
349+
assertNull(cache.pollChunk(256));
350+
}
351+
} catch (Throwable e) {
352+
error.compareAndSet(null, e);
353+
} finally {
354+
doneLatch.countDown();
355+
}
356+
}).start();
357+
}
358+
359+
startLatch.countDown();
360+
// With the == sentinel check, threads could livelock here.
361+
// With >= ordering, all scans terminate promptly.
362+
boolean finished = doneLatch.await(5, java.util.concurrent.TimeUnit.SECONDS);
363+
assertTrue(finished, "Concurrent scans should terminate within 5 seconds, not livelock");
364+
assertNull(error.get());
333365
}
334366
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.