@@ -247,7 +247,7 @@ private AdaptiveByteBuf allocate(int size, int maxCapacity, Thread currentThread |
247 | 247 | if (!FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals() || |
248 | 248 | IS_LOW_MEM || |
249 | 249 | (magazineGroups = threadLocalGroup.get()) == null) { |
250 | | - magazineGroups = sizeClassedMagazineGroups; |
| 250 | + magazineGroups = sizeClassedMagazineGroups; |
251 | 251 | } |
252 | 252 | if (index < magazineGroups.length) { |
253 | 253 | allocated = magazineGroups[index].allocate(size, maxCapacity, currentThread, buf); |
@@ -296,7 +296,7 @@ private AdaptiveByteBuf allocateFallback(int size, int maxCapacity, Thread curre |
296 | 296 | chunkRegistry.add(chunk); |
297 | 297 | try { |
298 | 298 | 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"; |
300 | 300 | } finally { |
301 | 301 | // As the chunk is an one-off we need to always call release explicitly as readInitInto(...) |
302 | 302 | // will take care of retain once when successful. Once The AdaptiveByteBuf is released it will |
@@ -316,7 +316,7 @@ private Magazine getFallbackMagazine(Thread currentThread) { |
316 | 316 | */ |
317 | 317 | void reallocate(int size, int maxCapacity, AdaptiveByteBuf into) { |
318 | 318 | 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"; |
320 | 320 | } |
321 | 321 |
|
322 | 322 | long usedMemory() { |
@@ -503,6 +503,7 @@ private void freeChunkReuseQueue(Thread ownerThread) { |
503 | 503 |
|
504 | 504 | interface ChunkCache { |
505 | 505 | Chunk pollChunk(int size); |
| 506 | + |
506 | 507 | boolean offerChunk(Chunk chunk); |
507 | 508 | } |
508 | 509 |
|
@@ -639,13 +640,16 @@ private SizeClassedChunk scanForCapacity() { |
639 | 640 | if (notEmptyCount > 0) { |
640 | 641 | SizeClassedChunk chunk = chunks[head]; |
641 | 642 | assert chunk.hasRemainingCapacity(); |
642 | | - chunk.purgeEpoch = 0; |
643 | 643 | chunks[head] = null; |
644 | 644 | head = (head + 1) & (chunks.length - 1); |
645 | 645 | count--; |
646 | 646 | notEmptyCount--; |
647 | 647 | return chunk; |
648 | 648 | } |
| 649 | + return scanForCapacityFallback(); |
| 650 | + } |
| 651 | + |
| 652 | + private SizeClassedChunk scanForCapacityFallback() { |
649 | 653 | int mask = chunks.length - 1; |
650 | 654 | int pos = (head + notEmptyCount) & mask; |
651 | 655 | int end = tail; |
@@ -710,6 +714,7 @@ private void closeGap(int kept) { |
710 | 714 |
|
711 | 715 | private void partition(int size) { |
712 | 716 | int mask = chunks.length - 1; |
| 717 | + // First pass: hasCapacity to front, noCapacity to back. |
713 | 718 | int lo = 0; |
714 | 719 | int hi = size - 1; |
715 | 720 | while (lo <= hi) { |
@@ -725,6 +730,22 @@ private void partition(int size) { |
725 | 730 | } |
726 | 731 | } |
727 | 732 | 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 | + } |
728 | 749 | } |
729 | 750 |
|
730 | 751 | @Override |
@@ -749,11 +770,11 @@ public String toString() { |
749 | 770 | int mask = chunks.length - 1; |
750 | 771 | StringBuilder sb = new StringBuilder(); |
751 | 772 | 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 "); |
757 | 778 | for (int i = 0; i < count; i++) { |
758 | 779 | if (i > 0) { |
759 | 780 | sb.append(", "); |
@@ -766,12 +787,40 @@ public String toString() { |
766 | 787 | String actual = c == null ? "null" : |
767 | 788 | c.hasRemainingCapacity() ? "hasCap" : "noCap"; |
768 | 789 | 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(']'); |
770 | 791 | } |
771 | 792 | return sb.toString(); |
772 | 793 | } |
773 | 794 | } |
774 | 795 |
|
| 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 > 0) as fallback |
| 804 | + * queue: [E>0, E>0, E=0, E>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 > 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 | + */ |
775 | 824 | static final class SharedSizeClassedChunkCache extends SizeClassedChunkCache { |
776 | 825 | // Must exceed CHUNK_REUSE_QUEUE (the retention floor) to leave room for burst absorption. |
777 | 826 | // TODO replace with an unbounded concurrent collection once available. |
@@ -808,30 +857,57 @@ private SizeClassedChunk scanForCapacity() { |
808 | 857 | if (first == null) { |
809 | 858 | return null; |
810 | 859 | } |
811 | | - if (first.hasRemainingCapacity()) { |
| 860 | + if (first.purgeEpoch == 0 && first.hasRemainingCapacity()) { |
812 | 861 | return first; |
813 | 862 | } |
| 863 | + if (first.hasRemainingCapacity()) { |
| 864 | + return scanForCapacitySlow(first); |
| 865 | + } |
814 | 866 | long generation = scanGeneration.incrementAndGet(); |
815 | 867 | first.lastScanGeneration = generation; |
816 | 868 | if (!queue.offer(first)) { |
817 | 869 | first.markToDeallocate(); |
818 | 870 | return null; |
819 | 871 | } |
| 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) { |
820 | 882 | SizeClassedChunk chunk; |
821 | 883 | while ((chunk = queue.poll()) != null) { |
822 | 884 | if (chunk.lastScanGeneration >= generation) { |
823 | 885 | if (!queue.offer(chunk)) { |
824 | 886 | chunk.markToDeallocate(); |
825 | 887 | } |
826 | | - return null; |
| 888 | + break; |
827 | 889 | } |
828 | 890 | 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 | + } |
830 | 901 | } |
| 902 | + chunk.lastScanGeneration = generation; |
831 | 903 | if (!queue.offer(chunk)) { |
832 | 904 | chunk.markToDeallocate(); |
833 | 905 | } |
834 | 906 | } |
| 907 | + if (fallback != null) { |
| 908 | + fallback.purgeEpoch = 0; |
| 909 | + return fallback; |
| 910 | + } |
835 | 911 | return null; |
836 | 912 | } |
837 | 913 |
|
@@ -1128,9 +1204,11 @@ public Chunk newChunkAllocation(int promptingSize, Magazine magazine) { |
1128 | 1204 |
|
1129 | 1205 | private static final class Magazine { |
1130 | 1206 | private static final AtomicReferenceFieldUpdater<Magazine, Chunk> NEXT_IN_LINE; |
| 1207 | + |
1131 | 1208 | static { |
1132 | 1209 | NEXT_IN_LINE = AtomicReferenceFieldUpdater.newUpdater(Magazine.class, Chunk.class, "nextInLine"); |
1133 | 1210 | } |
| 1211 | + |
1134 | 1212 | private static final Chunk MAGAZINE_FREED = new Chunk(); |
1135 | 1213 |
|
1136 | 1214 | private static final class AdaptiveRecycler extends Recycler<AdaptiveByteBuf> { |
@@ -1382,7 +1460,7 @@ void free() { |
1382 | 1460 |
|
1383 | 1461 | public AdaptiveByteBuf newBuffer() { |
1384 | 1462 | 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(); |
1386 | 1464 | buf.resetRefCnt(); |
1387 | 1465 | buf.discardMarks(); |
1388 | 1466 | return buf; |
@@ -1449,7 +1527,7 @@ static class Chunk implements ChunkInfo { |
1449 | 1527 | } |
1450 | 1528 | } |
1451 | 1529 |
|
1452 | | - Magazine currentMagazine() { |
| 1530 | + Magazine currentMagazine() { |
1453 | 1531 | return magazine; |
1454 | 1532 | } |
1455 | 1533 |
|
@@ -1489,7 +1567,7 @@ void markToDeallocate() { |
1489 | 1567 | } |
1490 | 1568 |
|
1491 | 1569 | private void retain() { |
1492 | | - RefCnt.retain(refCnt); |
| 1570 | + RefCnt.retain(refCnt); |
1493 | 1571 | } |
1494 | 1572 |
|
1495 | 1573 | protected boolean release() { |
@@ -1620,7 +1698,7 @@ static class SizeClassedChunk extends Chunk { |
1620 | 1698 | // making late-arriving releaseSegment calls on external threads arithmetically harmless. |
1621 | 1699 | private static final int DEALLOCATED = Integer.MIN_VALUE; |
1622 | 1700 | private static final AtomicIntegerFieldUpdater<SizeClassedChunk> STATE = |
1623 | | - AtomicIntegerFieldUpdater.newUpdater(SizeClassedChunk.class, "state"); |
| 1701 | + AtomicIntegerFieldUpdater.newUpdater(SizeClassedChunk.class, "state"); |
1624 | 1702 | private volatile int state; |
1625 | 1703 | private final int segments; |
1626 | 1704 | private final int segmentSize; |
@@ -2042,7 +2120,7 @@ public ByteBuf capacity(int newCapacity) { |
2042 | 2120 | allocator.reallocate(newCapacity, maxCapacity(), this); |
2043 | 2121 | oldRoot.getBytes(baseOldRootIndex, this, 0, oldLength); |
2044 | 2122 | chunk.releaseSegment(baseOldRootIndex, oldCapacity); |
2045 | | - assert oldCapacity < maxFastCapacity && newCapacity <= maxFastCapacity: |
| 2123 | + assert oldCapacity < maxFastCapacity && newCapacity <= maxFastCapacity : |
2046 | 2124 | "Capacity increase failed"; |
2047 | 2125 | this.readerIndex = readerIndex; |
2048 | 2126 | this.writerIndex = writerIndex; |
@@ -2479,8 +2557,9 @@ protected void deallocate() { |
2479 | 2557 | interface ChunkAllocator { |
2480 | 2558 | /** |
2481 | 2559 | * Allocate a buffer for a chunk. This can be any kind of {@link AbstractByteBuf} implementation. |
| 2560 | + * |
2482 | 2561 | * @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}. |
2484 | 2563 | * @return The buffer that represents the chunk memory. |
2485 | 2564 | */ |
2486 | 2565 | AbstractByteBuf allocate(int initialCapacity, int maxCapacity); |
|