|
49 | 49 | import java.util.Queue; |
50 | 50 | import java.util.concurrent.ConcurrentLinkedQueue; |
51 | 51 | import java.util.concurrent.atomic.AtomicInteger; |
| 52 | +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; |
52 | 53 | import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; |
53 | 54 | import java.util.concurrent.atomic.LongAdder; |
54 | 55 | import java.util.concurrent.locks.StampedLock; |
@@ -246,7 +247,7 @@ private static MagazineGroup[] createMagazineGroupSizeClasses( |
246 | 247 | * |
247 | 248 | * @return A new multi-producer, multi-consumer queue. |
248 | 249 | */ |
249 | | - private static Queue<Chunk> createSharedChunkQueue() { |
| 250 | + private static Queue<SizeClassedChunk> createSharedChunkQueue() { |
250 | 251 | return PlatformDependent.newFixedMpmcQueue(CHUNK_REUSE_QUEUE); |
251 | 252 | } |
252 | 253 |
|
@@ -511,7 +512,7 @@ private void freeChunkReuseQueue(Thread ownerThread) { |
511 | 512 | // that reference some thread local chunk |
512 | 513 | threadLocalChunk.ownerThread = null; |
513 | 514 | } |
514 | | - chunk.release(); |
| 515 | + chunk.markToDeallocate(); |
515 | 516 | } |
516 | 517 | } |
517 | 518 | } |
@@ -522,24 +523,23 @@ private interface ChunkCache { |
522 | 523 | } |
523 | 524 |
|
524 | 525 | private static final class ConcurrentQueueChunkCache implements ChunkCache { |
525 | | - private final Queue<Chunk> queue; |
| 526 | + private final Queue<SizeClassedChunk> queue; |
526 | 527 |
|
527 | 528 | private ConcurrentQueueChunkCache() { |
528 | 529 | queue = createSharedChunkQueue(); |
529 | 530 | } |
530 | 531 |
|
531 | 532 | @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(); |
536 | 539 | if (chunk == null) { |
537 | 540 | return null; |
538 | 541 | } |
539 | | - if (chunk.hasUnprocessedFreelistEntries()) { |
540 | | - chunk.processFreelistEntries(); |
541 | | - } |
542 | | - if (chunk.remainingCapacity() >= size) { |
| 542 | + if (chunk.hasRemainingCapacity()) { |
543 | 543 | return chunk; |
544 | 544 | } |
545 | 545 | queue.offer(chunk); |
@@ -549,7 +549,7 @@ public Chunk pollChunk(int size) { |
549 | 549 |
|
550 | 550 | @Override |
551 | 551 | public boolean offerChunk(Chunk chunk) { |
552 | | - return queue.offer(chunk); |
| 552 | + return queue.offer((SizeClassedChunk) chunk); |
553 | 553 | } |
554 | 554 | } |
555 | 555 |
|
@@ -633,7 +633,7 @@ public boolean offerChunk(Chunk chunk) { |
633 | 633 | break; |
634 | 634 | } |
635 | 635 | if (chunks.remove(key, toDeallocate)) { |
636 | | - toDeallocate.release(); |
| 636 | + toDeallocate.markToDeallocate(); |
637 | 637 | } |
638 | 638 | size = chunks.size(); |
639 | 639 | } |
@@ -1125,15 +1125,14 @@ void attachToMagazine(Magazine magazine) { |
1125 | 1125 | /** |
1126 | 1126 | * Called when a magazine is done using this chunk, probably because it was emptied. |
1127 | 1127 | */ |
1128 | | - boolean releaseFromMagazine() { |
| 1128 | + void releaseFromMagazine() { |
1129 | 1129 | // Chunks can be reused before they become empty. |
1130 | 1130 | // We can therefor put them in the shared queue as soon as the magazine is done with this chunk. |
1131 | 1131 | Magazine mag = magazine; |
1132 | 1132 | detachFromMagazine(); |
1133 | 1133 | if (!mag.offerToQueue(this)) { |
1134 | | - return release(); |
| 1134 | + markToDeallocate(); |
1135 | 1135 | } |
1136 | | - return false; |
1137 | 1136 | } |
1138 | 1137 |
|
1139 | 1138 | /** |
@@ -1143,6 +1142,10 @@ void releaseSegment(int ignoredSegmentId, int size) { |
1143 | 1142 | release(); |
1144 | 1143 | } |
1145 | 1144 |
|
| 1145 | + void markToDeallocate() { |
| 1146 | + release(); |
| 1147 | + } |
| 1148 | + |
1146 | 1149 | private void retain() { |
1147 | 1150 | RefCnt.retain(refCnt); |
1148 | 1151 | } |
@@ -1249,8 +1252,35 @@ public int size() { |
1249 | 1252 | } |
1250 | 1253 | } |
1251 | 1254 |
|
| 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 | + */ |
1252 | 1274 | private static final class SizeClassedChunk extends Chunk { |
1253 | 1275 | 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; |
1254 | 1284 | private final int segmentSize; |
1255 | 1285 | private final MpscIntQueue externalFreeList; |
1256 | 1286 | private final IntStack localFreeList; |
@@ -1260,6 +1290,8 @@ private static final class SizeClassedChunk extends Chunk { |
1260 | 1290 | SizeClassChunkController controller) { |
1261 | 1291 | super(delegate, magazine, true); |
1262 | 1292 | segmentSize = controller.segmentSize; |
| 1293 | + segments = controller.chunkSize / segmentSize; |
| 1294 | + STATE.lazySet(this, AVAILABLE); |
1263 | 1295 | ownerThread = magazine.group.ownerThread; |
1264 | 1296 | if (ownerThread == null) { |
1265 | 1297 | externalFreeList = controller.createFreeList(); |
@@ -1272,24 +1304,18 @@ private static final class SizeClassedChunk extends Chunk { |
1272 | 1304 |
|
1273 | 1305 | @Override |
1274 | 1306 | public boolean readInitInto(AdaptiveByteBuf buf, int size, int startingCapacity, int maxCapacity) { |
| 1307 | + assert state == AVAILABLE; |
1275 | 1308 | final int startIndex = nextAvailableSegmentOffset(); |
1276 | 1309 | if (startIndex == FREE_LIST_EMPTY) { |
1277 | 1310 | return false; |
1278 | 1311 | } |
1279 | 1312 | allocatedBytes += segmentSize; |
1280 | | - Chunk chunk = this; |
1281 | | - chunk.retain(); |
1282 | 1313 | 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; |
1293 | 1319 | } |
1294 | 1320 | return true; |
1295 | 1321 | } |
@@ -1310,30 +1336,37 @@ private int nextAvailableSegmentOffset() { |
1310 | 1336 | return startIndex; |
1311 | 1337 | } |
1312 | 1338 |
|
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 | + } |
1317 | 1347 | if (localFreeList != null) { |
1318 | | - assert Thread.currentThread() == ownerThread; |
1319 | | - remainingCapacity += localFreeList.size() * segmentSize; |
| 1348 | + return !localFreeList.isEmpty(); |
1320 | 1349 | } |
1321 | | - return remainingCapacity; |
| 1350 | + return !externalFreeList.isEmpty(); |
1322 | 1351 | } |
1323 | 1352 |
|
1324 | 1353 | @Override |
1325 | 1354 | 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(); |
1329 | 1364 | } |
1330 | | - int updatedRemainingCapacity = remainingCapacityOnFreeList(); |
1331 | | - if (updatedRemainingCapacity == remainingCapacity) { |
1332 | | - return remainingCapacity; |
| 1365 | + int updated = freeSegments * segmentSize; |
| 1366 | + if (updated != snapshotted) { |
| 1367 | + allocatedBytes = capacity() - updated; |
1333 | 1368 | } |
1334 | | - // update allocatedBytes based on what's available in the free list |
1335 | | - allocatedBytes = capacity() - updatedRemainingCapacity; |
1336 | | - return updatedRemainingCapacity; |
| 1369 | + return updated; |
1337 | 1370 | } |
1338 | 1371 |
|
1339 | 1372 | private void releaseSegmentOffsetIntoFreeList(int startIndex) { |
@@ -1348,8 +1381,45 @@ private void releaseSegmentOffsetIntoFreeList(int startIndex) { |
1348 | 1381 |
|
1349 | 1382 | @Override |
1350 | 1383 | 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); |
1353 | 1423 | } |
1354 | 1424 | } |
1355 | 1425 |
|
|