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 — Remove reference counting from size classed chunks (#16306) · netty/netty@a861106

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • buffer/src/main/java/io/netty/buffer
    • AdaptivePoolingAllocator.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
+116-46Lines changed: 116 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
import java.util.Queue;
5050
import java.util.concurrent.ConcurrentLinkedQueue;
5151
import java.util.concurrent.atomic.AtomicInteger;
52+
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
5253
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
5354
import java.util.concurrent.atomic.LongAdder;
5455
import java.util.concurrent.locks.StampedLock;
@@ -246,7 +247,7 @@ private static MagazineGroup[] createMagazineGroupSizeClasses(
246247
*
247248
* @return A new multi-producer, multi-consumer queue.
248249
*/
249-
private static Queue<Chunk> createSharedChunkQueue() {
250+
private static Queue<SizeClassedChunk> createSharedChunkQueue() {
250251
return PlatformDependent.newFixedMpmcQueue(CHUNK_REUSE_QUEUE);
251252
}
252253

@@ -511,7 +512,7 @@ private void freeChunkReuseQueue(Thread ownerThread) {
511512
// that reference some thread local chunk
512513
threadLocalChunk.ownerThread = null;
513514
}
514-
chunk.release();
515+
chunk.markToDeallocate();
515516
}
516517
}
517518
}
@@ -522,24 +523,23 @@ private interface ChunkCache {
522523
}
523524

524525
private static final class ConcurrentQueueChunkCache implements ChunkCache {
525-
private final Queue<Chunk> queue;
526+
private final Queue<SizeClassedChunk> queue;
526527

527528
private ConcurrentQueueChunkCache() {
528529
queue = createSharedChunkQueue();
529530
}
530531

531532
@Override
532-
public Chunk pollChunk(int size) {
533-
int attemps = queue.size();
534-
for (int i = 0; i < attemps; i++) {
535-
Chunk chunk = queue.poll();
533+
public SizeClassedChunk pollChunk(int size) {
534+
// we really don't care about size here since the sized class chunk q
535+
// just care about segments of fixed size!
536+
Queue<SizeClassedChunk> queue = this.queue;
537+
for (int i = 0; i < CHUNK_REUSE_QUEUE; i++) {
538+
SizeClassedChunk chunk = queue.poll();
536539
if (chunk == null) {
537540
return null;
538541
}
539-
if (chunk.hasUnprocessedFreelistEntries()) {
540-
chunk.processFreelistEntries();
541-
}
542-
if (chunk.remainingCapacity() >= size) {
542+
if (chunk.hasRemainingCapacity()) {
543543
return chunk;
544544
}
545545
queue.offer(chunk);
@@ -549,7 +549,7 @@ public Chunk pollChunk(int size) {
549549

550550
@Override
551551
public boolean offerChunk(Chunk chunk) {
552-
return queue.offer(chunk);
552+
return queue.offer((SizeClassedChunk) chunk);
553553
}
554554
}
555555

@@ -633,7 +633,7 @@ public boolean offerChunk(Chunk chunk) {
633633
break;
634634
}
635635
if (chunks.remove(key, toDeallocate)) {
636-
toDeallocate.release();
636+
toDeallocate.markToDeallocate();
637637
}
638638
size = chunks.size();
639639
}
@@ -1125,15 +1125,14 @@ void attachToMagazine(Magazine magazine) {
11251125
/**
11261126
* Called when a magazine is done using this chunk, probably because it was emptied.
11271127
*/
1128-
boolean releaseFromMagazine() {
1128+
void releaseFromMagazine() {
11291129
// Chunks can be reused before they become empty.
11301130
// We can therefor put them in the shared queue as soon as the magazine is done with this chunk.
11311131
Magazine mag = magazine;
11321132
detachFromMagazine();
11331133
if (!mag.offerToQueue(this)) {
1134-
return release();
1134+
markToDeallocate();
11351135
}
1136-
return false;
11371136
}
11381137

11391138
/**
@@ -1143,6 +1142,10 @@ void releaseSegment(int ignoredSegmentId, int size) {
11431142
release();
11441143
}
11451144

1145+
void markToDeallocate() {
1146+
release();
1147+
}
1148+
11461149
private void retain() {
11471150
RefCnt.retain(refCnt);
11481151
}
@@ -1249,8 +1252,35 @@ public int size() {
12491252
}
12501253
}
12511254

1255+
/**
1256+
* Removes per-allocation retain()/release() atomic ops from the hot path by replacing ref counting
1257+
* with a segment-count state machine. Atomics are only needed on the cold deallocation path
1258+
* ({@link #markToDeallocate()}), which is rare for long-lived chunks that cycle segments many times.
1259+
* The tradeoff is a {@link MpscIntQueue#size()} call (volatile reads, no RMW) per remaining segment
1260+
* return after mark — acceptable since it avoids atomic RMWs entirely.
1261+
* <p>
1262+
* State transitions:
1263+
* <ul>
1264+
* <li>{@link #AVAILABLE} (-1): chunk is in use, no deallocation tracking needed</li>
1265+
* <li>0..N: local free list size at the time {@link #markToDeallocate()} was called;
1266+
* used to track when all segments have been returned</li>
1267+
* <li>{@link #DEALLOCATED} (Integer.MIN_VALUE): all segments returned, chunk deallocated</li>
1268+
* </ul>
1269+
* <p>
1270+
* Ordering: external {@link #releaseSegment} pushes to the MPSC queue (which has an implicit
1271+
* StoreLoad barrier via its {@code offer()}), then reads {@code state} — this guarantees
1272+
* visibility of any preceding {@link #markToDeallocate()} write.
1273+
*/
12521274
private static final class SizeClassedChunk extends Chunk {
12531275
private static final int FREE_LIST_EMPTY = -1;
1276+
private static final int AVAILABLE = -1;
1277+
// Integer.MIN_VALUE so that `DEALLOCATED + externalFreeList.size()` can never equal `segments`,
1278+
// making late-arriving releaseSegment calls on external threads arithmetically harmless.
1279+
private static final int DEALLOCATED = Integer.MIN_VALUE;
1280+
private static final AtomicIntegerFieldUpdater<SizeClassedChunk> STATE =
1281+
AtomicIntegerFieldUpdater.newUpdater(SizeClassedChunk.class, "state");
1282+
private volatile int state;
1283+
private final int segments;
12541284
private final int segmentSize;
12551285
private final MpscIntQueue externalFreeList;
12561286
private final IntStack localFreeList;
@@ -1260,6 +1290,8 @@ private static final class SizeClassedChunk extends Chunk {
12601290
SizeClassChunkController controller) {
12611291
super(delegate, magazine, true);
12621292
segmentSize = controller.segmentSize;
1293+
segments = controller.chunkSize / segmentSize;
1294+
STATE.lazySet(this, AVAILABLE);
12631295
ownerThread = magazine.group.ownerThread;
12641296
if (ownerThread == null) {
12651297
externalFreeList = controller.createFreeList();
@@ -1272,24 +1304,18 @@ private static final class SizeClassedChunk extends Chunk {
12721304

12731305
@Override
12741306
public boolean readInitInto(AdaptiveByteBuf buf, int size, int startingCapacity, int maxCapacity) {
1307+
assert state == AVAILABLE;
12751308
final int startIndex = nextAvailableSegmentOffset();
12761309
if (startIndex == FREE_LIST_EMPTY) {
12771310
return false;
12781311
}
12791312
allocatedBytes += segmentSize;
1280-
Chunk chunk = this;
1281-
chunk.retain();
12821313
try {
1283-
buf.init(delegate, chunk, 0, 0, startIndex, size, startingCapacity, maxCapacity);
1284-
chunk = null;
1285-
} finally {
1286-
if (chunk != null) {
1287-
// If chunk is not null we know that buf.init(...) failed and so we need to manually release
1288-
// the chunk again as we retained it before calling buf.init(...). Beside this we also need to
1289-
// restore the old allocatedBytes value.
1290-
allocatedBytes -= segmentSize;
1291-
chunk.releaseSegment(startIndex, startingCapacity);
1292-
}
1314+
buf.init(delegate, this, 0, 0, startIndex, size, startingCapacity, maxCapacity);
1315+
} catch (Throwable t) {
1316+
allocatedBytes -= segmentSize;
1317+
releaseSegmentOffsetIntoFreeList(startIndex);
1318+
throw t;
12931319
}
12941320
return true;
12951321
}
@@ -1310,30 +1336,37 @@ private int nextAvailableSegmentOffset() {
13101336
return startIndex;
13111337
}
13121338

1313-
private int remainingCapacityOnFreeList() {
1314-
final int segmentSize = this.segmentSize;
1315-
int remainingCapacity = externalFreeList.size() * segmentSize;
1316-
IntStack localFreeList = this.localFreeList;
1339+
// this can be used by the ConcurrentQueueChunkCache to find the first buffer to use:
1340+
// it doesn't update the remaining capacity and it's not consider a single segmentSize
1341+
// case as not suitable to be reused
1342+
public boolean hasRemainingCapacity() {
1343+
int remaining = super.remainingCapacity();
1344+
if (remaining > 0) {
1345+
return true;
1346+
}
13171347
if (localFreeList != null) {
1318-
assert Thread.currentThread() == ownerThread;
1319-
remainingCapacity += localFreeList.size() * segmentSize;
1348+
return !localFreeList.isEmpty();
13201349
}
1321-
return remainingCapacity;
1350+
return !externalFreeList.isEmpty();
13221351
}
13231352

13241353
@Override
13251354
public int remainingCapacity() {
1326-
int remainingCapacity = super.remainingCapacity();
1327-
if (remainingCapacity > segmentSize) {
1328-
return remainingCapacity;
1355+
int remaining = super.remainingCapacity();
1356+
return remaining > segmentSize ? remaining : updateRemainingCapacity(remaining);
1357+
}
1358+
1359+
private int updateRemainingCapacity(int snapshotted) {
1360+
int freeSegments = externalFreeList.size();
1361+
IntStack localFreeList = this.localFreeList;
1362+
if (localFreeList != null) {
1363+
freeSegments += localFreeList.size();
13291364
}
1330-
int updatedRemainingCapacity = remainingCapacityOnFreeList();
1331-
if (updatedRemainingCapacity == remainingCapacity) {
1332-
return remainingCapacity;
1365+
int updated = freeSegments * segmentSize;
1366+
if (updated != snapshotted) {
1367+
allocatedBytes = capacity() - updated;
13331368
}
1334-
// update allocatedBytes based on what's available in the free list
1335-
allocatedBytes = capacity() - updatedRemainingCapacity;
1336-
return updatedRemainingCapacity;
1369+
return updated;
13371370
}
13381371

13391372
private void releaseSegmentOffsetIntoFreeList(int startIndex) {
@@ -1348,8 +1381,45 @@ private void releaseSegmentOffsetIntoFreeList(int startIndex) {
13481381

13491382
@Override
13501383
void releaseSegment(int startIndex, int size) {
1351-
release();
1352-
releaseSegmentOffsetIntoFreeList(startIndex);
1384+
IntStack localFreeList = this.localFreeList;
1385+
if (localFreeList != null && Thread.currentThread() == ownerThread) {
1386+
localFreeList.push(startIndex);
1387+
int state = this.state;
1388+
if (state != AVAILABLE) {
1389+
updateStateOnLocalReleaseSegment(state, localFreeList);
1390+
}
1391+
} else {
1392+
boolean segmentReturned = externalFreeList.offer(startIndex);
1393+
assert segmentReturned;
1394+
// implicit StoreLoad barrier from MPSC offer()
1395+
int state = this.state;
1396+
if (state != AVAILABLE) {
1397+
deallocateIfNeeded(state);
1398+
}
1399+
}
1400+
}
1401+
1402+
private void updateStateOnLocalReleaseSegment(int previousLocalSize, IntStack localFreeList) {
1403+
int newLocalSize = localFreeList.size();
1404+
boolean alwaysTrue = STATE.compareAndSet(this, previousLocalSize, newLocalSize);
1405+
assert alwaysTrue : "this shouldn't happen unless double release in the local free list";
1406+
deallocateIfNeeded(newLocalSize);
1407+
}
1408+
1409+
private void deallocateIfNeeded(int localSize) {
1410+
// Check if all segments have been returned.
1411+
int totalFreeSegments = localSize + externalFreeList.size();
1412+
if (totalFreeSegments == segments && STATE.compareAndSet(this, localSize, DEALLOCATED)) {
1413+
deallocate();
1414+
}
1415+
}
1416+
1417+
@Override
1418+
void markToDeallocate() {
1419+
IntStack localFreeList = this.localFreeList;
1420+
int localSize = localFreeList != null ? localFreeList.size() : 0;
1421+
STATE.set(this, localSize);
1422+
deallocateIfNeeded(localSize);
13531423
}
13541424
}
13551425

0 commit comments

Comments
0 (0)
You are visitor 01402775 — 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.