GeezerVison is showing github.com — Improve adaptive unshared size class allocation's fast-path · Issue #15530 · netty/netty
Improve adaptive unshared size class allocation's fast-path #15530DescriptionThanks to #15525 we've realized that there's still lot of room for the adaptive allocation fast-path and found lot of issues and unoptimized behaviours.
Let me summarize few of them in this issue so we can address them (eventually).
The reference benchmark is franz1981@bc334c9 which include a "fake" adaptive allocator which perform the same measured heavy (atomic) operations of the current adaptive allocator in the thread-local and size-class scenario.
By running this benchmark and profiling it vs adaptive allocator there are few issues:
too many (uncontended) atomics:
- hot: chunk retain/release (xadd, cas)
- hot: segment mpsc int q's offer (cas)
- cold: shared mpmc q's offer/polll
reference count checks for chunks fall off the optimized path of buffers:
(see #15525 (comment))
weird recycling behaviour:
The Recycler used for the thread local allocation of ByteBuf fail to inline its atomic int updater, see
and its cost is just too high compared to what's performed by Mimalloc (which is a linked list's top removal and link).
unspecialized logic
The thread-local (unshared) size-class magazine allocation path is not optimized for such context of execution:
- there's no need of a mpmc shared queue since no other threads can allocate "without locks" because there's no lock: we can use a mpsc one
- there's no need to aggressively release the chunk from the magazine as soon as it looks like there's not enough capacity: none can reuse it due to the previous point
- there's no need to know the exact size before attempting to "read into" chunk because for size chunks we just need to know if there's an available segment (this applies to shared ones as well)
- [TO BE VERIFIED] a chunk is marked to be deallocated only if it fails to be placed in the shared queue. This decision can be taken only by the owner thread. After that, it can just observe release of segments and no new allocations, because is not visible to anyone: this info could be used to simplify the reference scheme for chunk, saving chunk retain/releases (mentioned at the beginning of this issue)
Activitychanged the title [-]Improve adaptive thread local size class allocation's fast-path[/-] [+]Improve adaptive shared size class allocation's fast-path[/+] on Aug 8, 2025franz1981 commented on Aug 11, 2025 ContributorAuthor More actions I'm happy if you work on this w me @georgebanasios I have some idea, but having another brain will help for sure :) Reacted by George Banasios georgebanasios commented on Aug 11, 2025 @franz1981 Awesome, thanks! I'm definitely in and happy to collaborate.
I actually did some local experiments trying to improve the free-list performance and chunk ref-counting. It gave a slight boost, but as you said, there are deeper issues.
(Regarding storing the owner thread btw, I think storing the Magazine owner in the AdaptiveByteBuf and then on release checking the owner's localFreeList && checking the current thread's Magazine group, could avoid storing the thread).
MiMallocByteBufAllocator is just more optimized for the thread local path which aligns with your points in the ticket (like the unspecialized logic).
Curious to hear how you're thinking of approaching this. Reacted by Francesco Nigro franz1981 commented on Aug 11, 2025 ContributorAuthor More actions We do have some severe mix of penalties, including fast thread local's Recyclers usage while...we are already in a single threaded path :"(.
I'll write a PoC of the mix of changes for all the relevant parts to see how we perform in that bench - at the cost of having some broken logic too, just to understand if is possible - and a which cost. Reacted by George Banasios franz1981 commented on Aug 11, 2025 ContributorAuthor More actions for
(Regarding storing the owner thread btw, I think storing the Magazine owner in the AdaptiveByteBuf and then on release checking the owner's localFreeList && checking the current thread's Magazine group, could avoid storing the thread
The thing is that since we don't know which thread is calling the deallocation, we still need to make sure if we can even access the free list, but I'm opened to other suggestions; so feel free to share a branch with your idea 🙏 georgebanasios commented on Aug 11, 2025 Reacted by Francesco Nigro franz1981 commented on Aug 11, 2025 ContributorAuthor More actions @georgebanasios This is to have "fun"
https://github.com/franz1981/netty/tree/broken_adaptive
The result:
Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 10 16852645.748 ± 3148.290 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 10 13392388.848 ± 4750.899 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 10 17587780.987 ± 2031.331 ops/s
ByteBufAllocatorAllocPatternBenchmark.pooledDirect thrpt 10 5804717.918 ± 1551.802 ops/s
This was just a test to verify that we could get the same exact performance and I didn't improved the code to compute the remaining capacity nor saved the double lookup of size class (!) which has never been a good idea and I would love to improve it.
Can you verify the improvement is there @georgebanasios ?
Consider that this test need to run with something like
java -Djmh.executor=CUSTOM -Djmh.executor.class=io.netty.microbench.util.AbstractMicrobenchmark\$HarnessExecutor -jar microbench/target/microbenchmarks.jar io.netty.microbench.buffer.ByteBufAllocatorAllocPatternBenchmark.*Direct
The results are a good sign that we can get there and the bottlenecks were exactly what I've listed; I got an idea on how to implement a "special" reference count once a chunk is marked for deallocation but it will take me the whole tomorrow, likely.
But at least is clear that it was the main gap to fix.
In short this branch:
- remove the chunk retain/release: it could be implemented by adding a
markToDeallocate new method which set a new state tracking the local int stack size across thread and can be used to handle the fast-path (which doesn't need to deallocate the chunk) using the existing int stack/mpsc q + plain/volatile load of the state
- use a simple array q to recycle the chunk: it can be implemented correcntly as a linked list + concurrent list as mimalloc does OR array q + mpsc q local to the not shareable magazine
- Since the chunk updater is not used we have saved it NOT getting inlined, as a bonus
I need to:
Reacted by old driver Reacted by George Banasios laosijikaichele commented on Aug 11, 2025
https://github.com/franz1981/netty/tree/broken_adaptive
I cloned the code, and run the benchmark, but got OOM error:
# Benchmark: io.netty.microbench.buffer.ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect
# Run progress: 0.00% complete, ETA 00:04:40
# Fork: 1 of 2
# Warmup Iteration 1: <failure>
java.lang.OutOfMemoryError: Cannot reserve 540672 bytes of direct buffer memory (allocated: 805101569, limit: 805306368)
at java.base/java.nio.Bits.reserveMemory(Bits.java:178)
at java.base/java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:111)
at java.base/java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:363)
at io.netty.util.internal.CleanerJava9.allocate(CleanerJava9.java:86)
at io.netty.util.internal.PlatformDependent.allocateDirect(PlatformDependent.java:600)
at io.netty.buffer.UnpooledDirectByteBuf.allocateDirectBuffer(UnpooledDirectByteBuf.java:121)
at io.netty.buffer.UnpooledDirectByteBuf.<init>(UnpooledDirectByteBuf.java:66)
at io.netty.buffer.UnpooledUnsafeDirectByteBuf.<init>(UnpooledUnsafeDirectByteBuf.java:42)
Did I miss configured something? Reacted by Francesco Nigro georgebanasios commented on Aug 11, 2025 Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 20 53083327.934 ± 3478576.999 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 20 56173174.243 ± 1866510.743 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 20 52832143.096 ± 2228754.122 ops/s
ByteBufAllocatorAllocPatternBenchmark.pooledDirect thrpt 20 16823734.161 ± 526860.341 ops/s
Reacted by Francesco Nigro franz1981 commented on Aug 11, 2025 ContributorAuthor More actions @laosijikaichele since it is not dealing with failure to insert it into the shared q, I think, depending by the machine, to need more capacity for the shared queue, to work. Let me check franz1981 commented on Aug 11, 2025 ContributorAuthor More actions io.netty.allocator.chunkReuseQueueCapacity this could be set quite high to save having any failure to offer into it laosijikaichele commented on Aug 11, 2025
io.netty.allocator.chunkReuseQueueCapacity this could be set quite high to save having any failure to offer into it
Yes, I enlarged it to 8 * 1024, and no OOM occured:
Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 10 35601429.975 ± 40300.682 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 10 31993584.778 ± 106996.231 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 10 34443044.669 ± 53822.246 ops/s
The results seems very good! 👍 Reacted by Francesco Nigro georgebanasios commented on Aug 14, 2025 With latest commits on mimalloc and deallocation (franz1981@cce8673)
Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 20 47041938.519 ± 2057118.560 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 20 55025946.653 ± 828425.378 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 20 55674382.179 ± 1370834.509 ops/s
ByteBufAllocatorAllocPatternBenchmark.pooledDirect thrpt 20 17450323.976 ± 314722.449 ops/s
Reacted by Francesco Nigro franz1981 commented on Aug 14, 2025 ContributorAuthor More actions Thanks @georgebanasios I'm not getting locally the same gap, but I see we have few atomic operations in the "unshared path" and it is mostly the cause of this performance difference, but is much better than when we started. I leave you all the fun of making this fly, enjoy!
Important Note:
#15530 (comment) shows that we maybe have a bug in the way we compute the remaining capacity - because size classed chunks receive request of allocations equals to segment size which should make impossible the retirement to happen in that code path.
This, unless the current chunk to use is empty and picked from the chunk reuse queue (since they don't deallocate!):
If it is the case it is still in line with the issue description which advocate for a unoptimized logic for size classes allocations.
In short, when the allocator need to reuse a chunk, it can perform a bad decision (hitting a still empty chunk), which will be then detached from the magazine right after.
This type of problem is more related the logic behind this allocator, since others (like mimalloc) have a global free list while here the different chunk's free list are scattered in the chunk reuse queue, increasing the chance to search for the right one (not empty) to pick.
Any idea @laosijikaichele and @georgebanasios on how to improve it, if I am right, is welcome Reacted by George Banasios georgebanasios commented on Aug 15, 2025 georgebanasios@79f1998
I'm trying to address the rest of the comments on this commit and test the performance.
I've included the following:
- remaining capacity check still read size from the external q: this could be improved with ease
- there's still a
state volatile load on segment release which could affect performance in the specific benchmark there since it force all fields after it to be loaded (causing more bound checks and other quirks): this could be saved by using VarHandle to perform a relaxed load or just add an additional boolean isAvailable field which can be used on unshared chunks to mirror a mark to deallocation state change
- the memory footprint should better share more of the recycling queues (especially for the un-shared magazines; they can use a single pair of queues shared among all magazine groups per owner thread. The shared magazines are fine.
I'm not getting the same performance as the previous PoC since I've added new behaviours (as mentioned above), but compared to the original code, should be far better.
and this: #15530 (comment)
Also, on the magazine I added a nextInLine for the thread-local path to test it out.
Results:
Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 20 53598524.156 ± 509554.095 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 20 57187212.030 ± 860078.602 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 20 57694313.924 ± 351608.919 ops/s
ByteBufAllocatorAllocPatternBenchmark.pooledDirect thrpt 20 17235094.284 ± 342512.383 ops/s
Before checking the remaining capacity computation, I want to actually determine if it's possible to replace the racy state design but keep the markToDeallocate logic, with a single atomic integer that tracks the number of segments that are currently allocated and in use. That should also eliminate all .size() calls and simplify the remaining capacity calculation. Reacted by Francesco Nigro Reacted by Francesco Nigro franz1981 commented on Aug 15, 2025 ContributorAuthor More actions This is getting there @georgebanasios I added few comments but beware, reading from phone...
In any case this is a new idea for u i.e. the shared chunk queue could be replaced by:
- a thread local priority queue which order the chunks based on the free list size (or just a FIFO array deque too, is fine) as perceived while draining from the external one
- an external mpsc shared chunk queue
If we can just use the thread local one, better, because it is freed only once the thread local is gone.
If we need to coordinate from both is possible but more complex, since we need to enforce the total size to be correct; again, not trivial, but possible.
This will remove the last existing concurrent operation, likely getting on par or better(?) than mimalloc.
The other interesting topic is to not affect the performance of the shared case, but is for another day. Reacted by George Banasios changed the title [-]Improve adaptive shared size class allocation's fast-path[/-] [+]Improve adaptive unshared size class allocation's fast-path[/+] on Aug 16, 2025franz1981 commented on Aug 16, 2025 ContributorAuthor More actions @georgebanasios I had some time to debug found something interesting and expected (?).
- the unshared size classed case very rarely (never: only on FULL chunk deallocation!) benefit from using
next_in_line because chunks often end up in the chunk reuse queue: which means that having a faster chunk reuse q is KEY to get faster (and this include my suggestion in the priority q for Improve adaptive unshared size class allocation's fast-path #15530 (comment)) and we could "just" replace the getAndSet with a getNextInline != nul && getAndSetNextInline to get faster in that path
- the attach/detach from magazin counters are hot because we have to iterate in the chunk reuse queue searching for some with "enough" available capacity: as said, just performing a better decision there would be better. But having a faster counter would help as well
Reacted by George Banasios georgebanasios commented on Aug 16, 2025
@georgebanasios I had some time to debug found something interesting and expected (?).
- the unshared size classed case very rarely (never: only on FULL chunk deallocation!) benefit from using
next_in_line because chunks often end up in the chunk reuse queue: which means that having a faster chunk reuse q is KEY to get faster (and this include my suggestion in the priority q for Improve adaptive unshared size class allocation's fast-path #15530 (comment)) and we could "just" replace the getAndSet with a getNextInline != nul && getAndSetNextInline to get faster in that path
Regarding the chunk reuse queue this is the next thing I'll change.
Right now, I've split the Magazine into 2 concrete implementations: Shared and ThreadLocal (no dedicated one for size classes yet just to see how it performs)
The results are:
Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 20 59189164.359 ± 2632968.006 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 20 57275905.786 ± 859620.935 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 20 55421217.734 ± 805117.195 ops/s
ByteBufAllocatorAllocPatternBenchmark.pooledDirect thrpt 20 17032686.329 ± 263879.217 ops/s
(Mind you these results are without points 3,4 from this: #15530 (comment). I reverted those fixes because I'm not sure if they were correct or not. I'll leave them for last)
I'll make the chunk reuse queue change and I'll push a new commit tomorrow along with the above change.
for:
- the attach/detach from magazine counters are hot because we have to iterate in the chunk reuse queue searching for some with "enough" available capacity: as said, just performing a better decision there would be better. But having a faster counter would help as well
At the moment I have it just with lazy set on fast path and atomic on shared.
Do you think it's worth on chunk deallocation to check if it has enough capacity to be worth keeping otherwise don't offer to q? or change the counter to LongAdder. laosijikaichele commented on Aug 17, 2025 Great job, I've been busy recently, will make time to look into these. Reacted by Francesco Nigro and George Banasios franz1981 commented on Aug 17, 2025 ContributorAuthor More actions No worries @laosijikaichele ❤️
There are plenty of interesting ideas from mimalloc which can be brought in IMO.
I have built the fake allocator in some of these branchs to enable who wanna play with it, to experiment with different prototypes using different performing techniques (e.g. using a linked list with double scheme as mimalloc does or an array dequeue, additional ref counting, etc etc) and get an immediate feedback of how it performs.
Once the single threaded unshared path is fully optimized (I have surely made wrong the usage of a lambda's handle whilst you can have the magazine itself to implement it and save loading twice the owner thread), I would suggest to check for the allocate in one thread (likely a fast thread local one) and deallocate on an another one - borrowing ideas from mimalloc e.g.
- doubling containers for uncontended vs lock free handling, separated (next in line could be make like that accepting a small additional footprint...)
- using uncontended ticks to operate on costly resources (the lock free structures): we do already this for the histograms so I don't see why we shouldn't do the same for other resources
Funny enough this could be emulated too without thread handoff playing with the primitives which make a fast thread local thread to mark a runnable as "special". georgebanasios commented on Aug 17, 2025 franz1981 commented on Aug 17, 2025 ContributorAuthor More actions @georgebanasios I have added few comments on the commit to improve further perf Reacted by George Banasios georgebanasios commented on Aug 18, 2025 Made some adjustments on this commit: georgebanasios@2fce306
It has the previous fixes, plus, addresses some of your comments @franz1981 .
Benchmark Mode Cnt Score Error Units
ByteBufAllocatorAllocPatternBenchmark.adaptiveDirect thrpt 20 63481480.628 ± 1078213.652 ops/s
ByteBufAllocatorAllocPatternBenchmark.fakeDirect thrpt 20 51253428.939 ± 4604563.462 ops/s
ByteBufAllocatorAllocPatternBenchmark.mimallocDirect thrpt 20 56722730.119 ± 627489.090 ops/s
ByteBufAllocatorAllocPatternBenchmark.pooledDirect thrpt 20 16892936.201 ± 355183.771 ops/s
franz1981 commented on Aug 18, 2025 ContributorAuthor More actions I will take a look tonight 🙏 numbers look better! @georgebanasios
If you want you can run a benchmark by omitting the harness executor which will go to the normal shared path so you can see if you have regressed there or not.
Another interesting experiment would be to create a warmup phase on setup which call the benchmarked method a configurable amount of time from both a fast and not fast thread local thread to enable the JIT to compile and use both classes of magazine and pollute the call sites and branches in both with equal probability, to see if the performance degrade.
Mimalloc is way more stable there since it doesn't behave differently but has only the thread local path, by design.
There is another bench written by @laosijikaichele which handoff allocations to be released in a different thread, but we can check this as a separate effort. Reacted by George Banasios chrisvest commented on Aug 19, 2025 @georgebanasios Interested in opening a PR in draft? Might be easier to follow the changes that way. But feel free to wait if you think it's too early. Reacted by George Banasios and Francesco Nigro georgebanasios commented on Aug 19, 2025 @chrisvest You're right it's a bit difficult to follow the changes, especially since these commits don't include the initial ones.
Since @franz1981 initiated the refactoring and the ticket, maybe it's better to wait for his input on how we should move forward with it once he returns. (there's a small regression I think on the shared path due to the shared q, I don't know if you want to handle this on the same PR, or in a separate one. Mimalloc performs on the shared path a lot better.)
Edit: I fixed the shared path locally and now it's slightly better than the original one. We can review on the commit.
In the meantime, to make it easier to review, in the next commit I'll include the complete diff.
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|