Repository navigation
4.2 per magazine cache - #17047
4.2 per magazine cache#17047franz1981 wants to merge 6 commits into
Conversation
|
FYI @laosijikaichele since I'm using CLQ if Unsafe is NOT available, you have to pass |
|
Wow I have experimented with removing the allocation on magazine without lock and...it improves concurrent behaviour by removing contention over the mpmc array queue used by the magazine recycler. |
Since I use Java 21, so it should not matter. |
To disable
|
|
@laosijikaichele thanks!
|
|
And more: magazine owned buffer deallocations are always paying the multi producer cost of recyclers, but...if we remember the magazine where the chunk is coming from, we could attempt locking the magazine and just release into a local array instead, saving the atomic operation to compete with other platform threads which has allocated from the same magazine and are releasing on the same recycler. |
I think this should work, mimalloc uses similar logic on the release path: https://github.com/neoionet/netty-allocator/blob/cb6058c443fa8fa6713f3a76d9d2663305be1aea/mimalloc/src/main/java/io/github/neoionet/netty/mimalloc/MiMallocByteBufAllocator.java#L1956-L1994 |
I think it's a smart move as well (well done to have thought of it!) because it is a good way to exploit what is a common pattern and still get the lock-free benefits of releases, if not possible |
92a9db9 to
c49092e
Compare
|
I've changed something so @laosijikaichele can you give it a shot? It should help both latencies and RSS |
Introduce SharedMagazineRef to decouple StampedLock from Magazine lifecycle. Magazine fields (chunkController, chunkCache, recycler) are always fully initialized - no null checks on the hot path. Magazines are lazily allocated via volatile reference with intent-revealing tryAllocate/free methods.
Remove allocateWithoutLock path - all magazine access goes through tryAllocate under StampedLock. Replace nextInLine volatile + AtomicRef with plain field (all access under lock). Eagerly init magazine 0. Decouple fallback allocation from Magazine - new Chunk constructor takes AdaptivePoolingAllocator directly. Inline newFallbackBuffer to use the shared fallbackRecycler (MPMC, truly contended) directly instead of routing through MagazineGroup. Add MPSC recycler variant to Recycler using MpscChunkedArrayQueue - used for per-magazine recyclers where the single consumer is under the lock. The shared fallbackRecycler stays MPMC (MpmcArrayQueue).
…ClassedChunkCache Each magazine now gets its own ThreadLocalSizeClassedChunkCache (ring buffer, no atomics) instead of sharing the group-level concurrent cache. This eliminates CAS contention on the chunk cache hot path for size-classed allocations. The buddy path (sizes > 16896) continues using the group-level ConcurrentSkipListChunkCache since those allocations are infrequent and the cache needs cross-magazine visibility. Remove SharedSizeClassedChunkCache and MpmcUnboundedXaddArrayQueue dependency - dead code now that all size-class caches are per-magazine. Inline newFallbackBuffer, remove stale comments and constants.
c49092e to
43399c4
Compare
…rentThread` and `originGroup`.
| public ChunkCache createChunkCache(boolean isThreadLocal) { | ||
| return SizeClassedChunkCache.create(isThreadLocal); | ||
| public ChunkCache createChunkCache() { | ||
| return new ThreadLocalSizeClassedChunkCache(); |
There was a problem hiding this comment.
The name is not great, it can be just SizeClassedChunkCache and the doc can say (it is AFAIK) it is not thread safe to access it concurrently by many threads.
| this.chunkController = group.chunkManagementStrategy.createController(group); | ||
| this.chunkCache = group.chunkManagementStrategy.hasPerMagazineCache() ? | ||
| group.chunkManagementStrategy.createChunkCache() : null; | ||
| this.recycler = isThreadLocal ? null : AdaptiveRecycler.sharedMpsc(MAGAZINE_BUFFER_QUEUE_CAPACITY); |
There was a problem hiding this comment.
This could collapse to use the thread local one instead of using EVENT_LOOP_LOCAL_BUFFER_POOL too
| // In any case we will store the Chunk as the current so it will be used again for the next allocation and | ||
| // thus be "reserved" by this Magazine for exclusive usage. | ||
| curr = NEXT_IN_LINE.getAndSet(this, null); | ||
| curr = nextInLine; |
There was a problem hiding this comment.
In theory since is not used across threads there's little point to use an atomic here, correct @chrisvest ?
Currently only the ARM server is available, I run the benchmark with you latest commit,
|
|
thanks @laosijikaichele That's on 861812e I suppose? |
Since the adaptive showed high RSS when live buffers is 128, I checked the JFR file, seems the frequent Mpsc-queue resizing cause it? Maybe we can use a fixed capacity for it? |
|
Thanks @laosijikaichele yeah I think I should size them differently ! Good finding |
The shared MPSC recycler (per-magazine ByteBuf wrapper pooling) was using MpscChunkedArrayQueue which allocates new Object[] chunks as it grows. With 32 threads and 128 live buffers per thread on API_GATEWAY pattern, this produced 671 Object[] allocation samples (3.7 B/op) from resize. Switch to MpscArrayQueue (fixed capacity, single pre-allocated array). No resize, no Object[] allocations after init. Verified with JFR: 0 Object[] allocation samples, 0.010 B/op.
|
@laosijikaichele addressed via 1bc90a3 thanks. |
|
@laosijikaichele FYI https://github.com/franz1981/netty/tree/4.2_chunk_recycling This is an attempt to bring from mimalloc few interesting ideas:
It doesn't fix yet the buddy allocator (which means we still have some cases of churning), but the performance seems much much better - and RSS as well Let me know wdyt so I can refine it further and eventually open a PR based on this alternative design |
|
I have run a quick JMH benchmark for verification, only compared
@franz1981 As you said, the adaptive seems improved a lot on both performance and RSS. 👍 |
|
I have to clean up the impl @laosijikaichele and probably will make the buddy allocation NOT to be shared across striped heaps (which is what you get in mimalloc BTW...) and I will make that branch to replace this draft PR, wdyt? |
Based on the numbers we currently get, I think it's worth trying. |
|
@laosijikaichele it seems the problem with the skip list for buddy allocations is the capacity. With 32 cores you have 64 slots and a shared one evict too aggressively buffers (which have ref cnt > 1) . |
|
ok @laosijikaichele despite I would like to make the skip list thread local, I prefer to ask @chrisvest to fix it as I don't have enough confidence re it: I've created 1ff87f3 which add a tiny change in the buddy cache to release only chunks which are already fully refilled: I don't like this solution tbh because it is not releasing "idle" and "useless" chunks, as we do for size classes, but is better than what we have which can too aggressively prune actively used chunks (which have live buffers which craved some memory out of them). my numbers with 32 cores and 64 Gb memory and platform threads with heap buffers and the ratio of latencies are similar to yours I still believe that both the evinction and capacity floor un buddy chunk cache to be bad.... NOTE thanks to this investigation I've found an important gap in the size class chunk cache: if the allocator is too quick to release a segment, all the allocations will end up being absorbed by the same chunk, over and over, without rotating to another chunk and querying the cache, which makes it unable to idle and age any of the chunks it contains, which clearly, is not ideal. |
|
One qq for you @laosijikaichele in order to enable notification on releases which can trigger purging pages, mimalloc retain as owner thread the one which enter the lock, which can leak VTs with loom (and regardless is not a safe assumptions on Platform thread too..). It could be solved just via acquiring the stamped lock and once there can still safely purge, but it is going to harm concurrency in case the release happen on a different platform thread (which can happen with loom: a VT allocate something and send a write and flush back to the originating event loop which will be responsible to release..) so I am not sure the benchmark excercize a common case... Did you noticed the temporary leak of owner thread and the use case I mentioned? |
Currently, on allocation(producer) side, mimalloc periodically(using the heartbeat mechanism) collect the deferred releasing memory. |
|
@laosijikaichele The last time I have checked it looks like mimalloc retain a strong reference to the owner thread for a segment. It means that if the segment won't be released or passed to other Threads which delay releasing it, can leak (temporarly) it, causing excessive GCs and promotion - which can be quite dangerous with VirtualThread(s) i.e. VT once promoted requires to allocate a fresh new StackChunk on the first parking/yield, attaching the previous stack chunk (in old gen) in a sort of linked lists of stack chunks. Anyway, the current state of 1ff87f3 seems good enough for a PR; i will further polish it and add some guard to help with OOM I've seen reported recently, with 1 core and small memory (the so called "low memory" use case), because the floor of 128 chunks retained per chunk cache seems to be way too much for adaptive. |
Yes, that's a good point 👍. |

Fixes #17028
This is introducing few changes:
@laosijikaichele this is not solving the buddy cache issue - which BTW, could benefit as well by the 5th point (I know it would, with the benchmark you provided), but it won't be enough to fix all the gaps.