Repository navigation
Conversation
a40264c to
ab8d7a3
Compare
|
@laosijikaichele ^^ still working on it, but the idea is the same of mimalloc pages lists |
549214a to
95d91d6
Compare
|
The idea Is simple:
My personal take is that the current solution which limit the reuse chunk cache harm more than what it solves, as using malloc/free just move the "problem" to the native allocator, which would further make it invisible to the application writer. Any thoughts @chrisvest @laosijikaichele ? |
bbfc0c8 to
4bbb4e5
Compare
|
I think @laosijikaichele this is ready to be reviewed:
In general, I don't want anymore malloc/free to be the solution of the RSS problem - since they can just make things much worse ^^ I would instead implement the concept of periodic sweeping enforcing soft limits, using background sweeper thread(s) - which could play nicely with native heap trimming |
There was a problem hiding this comment.
Pull request overview
This PR replaces the size-class chunk reuse mechanism in Netty’s adaptive pooling allocator. It removes the bounded queue + scanning approach and introduces a notification-driven “parking lot” cache (inspired by mimalloc-style sharded free lists) to reuse exhausted chunks in O(1) once segments are returned, aiming to reduce chunk churn on low-core environments.
Changes:
- Replaced the size-class
ConcurrentQueueChunkCachereuse queue withParkingLotChunkCacheusing intrusive ready/cleanup lists and segment-return notifications. - Updated
SizeClassedChunkstate machine to support “armed” chunks and ready-list publication on first segment return. - Added allocator tests that validate chunk reuse and memory stabilization across allocation cycles (plus a benchmark-like reuse pattern test).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.
| File | Description |
|---|---|
| buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java | Implements the new parking-lot chunk cache and notification/disarm flow for size-class chunks; removes the bounded reuse queue. |
| buffer/src/test/java/io/netty/buffer/AdaptiveByteBufAllocatorTest.java | Adds tests to detect chunk loss/churn and validate memory stabilization across reuse cycles. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| @Test | ||
| void benchmarkPatternChunkReuse() throws Exception { | ||
| AdaptiveByteBufAllocator allocator = newAllocator(false); | ||
|
|
There was a problem hiding this comment.
@chrisvest FYI. It's a good test but can be intensive ^^
| SizeClassedChunk head; | ||
| do { | ||
| head = cleanupHead; | ||
| if (head == null) { |
There was a problem hiding this comment.
This requires some check - but it should be correct - once found to be null it means free has already kicked in and the caller is than responsible of mark for deallocation as no other will do it
64369d4 to
cd53409
Compare
Just a rough idea: for periodic sweeping, it might be worth considering a mimalloc-style 'heartbeat' approach. Maybe we can piggyback chunk trimming onto certain periodic, deterministic, non-hot-path operations, avoiding the need for a dedicated background thread. This could be a simpler starting point before we introduce a sweeper thread. |
|
That's ok to me @laosijikaichele it's a good feedback and yes: but not on this PR, which is already complex. |
cd53409 to
348e03a
Compare
…ive lists Motivation: The bounded ConcurrentQueueChunkCache causes chunk malloc/free churn on low-core containers and costs O(n) scanning to find chunks with available segments. Modification: Replace with a notification-driven ParkingLotChunkCache inspired by mimalloc's free-list sharding. Exhausted chunks are armed and the first segment return pushes them to a ready list for O(1) reuse. A push-once MPSC cleanup list with sentinel terminal handles shutdown cleanup. Owner-thread segment returns bypass the Treiber stack and write directly to the local ready list drain chain. Result: Eliminates chunk churn and O(n) scanning.
Guard NEXT_IN_LINE.getAndSet and READY_HEAD.getAndSet with a plain volatile read first. When the field is null (common case for thread-local allocations), the cheap volatile read skips the expensive xchg entirely.
Verify that a chunk created on a thread-local magazine, never exhausted (never offered to the cache or registered in the cleanup list), is properly deallocated when the thread dies and all segments are returned externally.
Add two tests covering the cleanup list paths: - cleanupListDeallocatesAllChunksOnThreadDeath: exhausts multiple chunks (registered in cleanup list) plus a partial current chunk. On thread death, freeChunksThreadLocal walks the cleanup list and the magazine free path handles the current chunk. The idempotent markToDeallocate CAS prevents double-free when a chunk appears in both paths. - sharedCleanupListDeallocatesOnFinalization: exercises the shared magazine path where cleanup only happens on allocator finalization. Allocates and releases all buffers, then verifies the allocator is GC'd and finalized (via WeakReference), confirming freeChunksShared walked the cleanup list.
348e03a to
b29f243
Compare
hasRemainingCapacity reads the non-thread-safe localFreeList, so disarmIfSegmentsAvailable must be called from the owner thread for thread-local chunks. Shared chunks are inherently safe (localFreeList is null).
Benchmark environment
JMH throughput (heap, 2 cores, HarnessExecutor — thread-local path)
2.5x throughput. GC allocation churn drops from 1698 B/op to effectively zero. AllocationPatternSimulator (Apple WebSocket proxy pattern, 4 threads, 60s)
Heap buffers — Adaptive vs Pooled at steady state (t=60)
The old adaptive allocator at 1024 live buffers used roughly the same memory as pooled (32 MiB vs 33 MiB) — chunk churn negated its advantage. The new code uses 2.2x less memory than pooled at 1024 live buffers. Direct buffers — solo adaptive config (
|
| Metric | Before | After | Reduction |
|---|---|---|---|
| usedDirectMemory peak | 35,784 KiB | 14,648 KiB | -59% |
Both heap and direct show the same improvement: ~60% fewer live chunk bytes at peak.
Root cause
Thread-local magazines exhaust chunks completely before any segments return. With the bounded MPMC reuse queue (capacity = max(2, availableProcessors * 2) = 4 on 2 cores), dead chunks fill the queue. pollChunk cannot find a reusable one (O(n) scan, all exhausted). New chunks are malloc'd, old ones overflow and get markToDeallocate'd. The notification-driven cache eliminates this: exhausted chunks are armed, the first segment return triggers O(1) notification, and chunks are reused immediately.
Note on memory retention
The new code never frees chunks — they are retained in the cache and reused indefinitely. For stable workloads this is ideal (chunk count stabilizes, no malloc/free overhead). For bursty workloads where traffic spikes create many chunks and then drops, peak memory is retained. The default PooledByteBufAllocator handles this differently — it frees empty chunks when they reach 0% usage in q000. A bounded eviction policy for idle chunks could be added as a follow-up if needed.
|
One additional note @laosijikaichele this patch is using a FIFO strategy to put reusable (with available segments) chunks into the ready list - which doesn't account in any form that they will have "enough" segments really, or the highest number. But it seems to me that FIFO can give, if there're many ready, enough "room" that more segments will be pushed in oldest ones, so it should still be decent. |
|
@laosijikaichele How mimalloc does it: pages are embedded in fixed-size segments (64 pages per 4 MiB segment). When a page becomes empty, its backing memory is purged ( Our situation: chunks are tracked in a flat singly-linked cleanup list (push-once, Options for a follow-up:
The natural heartbeat point would be |
|
@franz1981 For the allocation pattern simulator, are you able to see the private repo https://github.com/netty/netty-allocator-profiles ? The e-commerce profile is my preferred go-to profile these days. It was made with a larger and more realistic sampling. |
|
@chrisvest page not found! |
Permissions fixed. Should be accessible now. |
Not a fan of this one, because it sounds very similar to how we deallocated chunks in the past; e.g. only when all allocated buffers are freed. This is on a higher level looking at chunk groups instead of individual chunks, but I still don't think it'll be profitable in practice. |
E-commerce JFR pattern (from netty-allocator-profiles)
Peak usedHeapMemory
Adaptive(1024) steady-state (t=10..30 avg)
The e-commerce pattern shows a more modest improvement than the WebSocket proxy pattern (17% vs 60%). This is expected — the e-commerce workload has more diverse allocation sizes spread across many size classes, with less concentrated chunk exhaustion per class. The WebSocket proxy pattern has heavy concentration on a few sizes (256, 1024, 16639) which exhausts chunks faster on 2 cores. |
|
I am exploring an alternative less invasive change which make possible to release some memory to the OS, but I think it should be opt-in. I am not sure is a good idea to release memory back to the OS because without trimming on native heap it won't lower RSS and is not guaranteed will be available to the allocator for further allocation either (as it depends by the native allocator under the hood). Ideas @laosijikaichele ? |
I think your point makes sense, how about we do this:
Conceptually, this large chunk is similar to a segment in mimalloc. |
|
FYI @chrisvest and @laosijikaichele wdyt? This is even malloc/free AND it has similar performance benefits of this same PR |
|
The epoch-based approach perform better and permit chunks to be released back to the OS. Shall we focus on that approach? |
Motivation:
The bounded ConcurrentQueueChunkCache causes chunk malloc/free churn on
low-core containers and costs O(n) scanning to find chunks with available
segments.
Modification:
Replace with a notification-driven ParkingLotChunkCache inspired by
mimalloc's free-list sharding.
Result:
Eliminates chunk churn and O(n) scanning.