Skip to content

Unified StripedHeap model, size-class chunk recycling and allocation-driven purge - #17151

Open
franz1981 wants to merge 31 commits into
netty:4.2from
franz1981:4.2_chunk_recycling
Open

franz1981 wants to merge 31 commits into
netty:4.2from
franz1981:4.2_chunk_recycling

Conversation

@franz1981

@franz1981 franz1981 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Motivation:

Existing performance tests shows adaptive striping model and sharing across size classes to under-perform compared to other alternatives.
In addition, the existing striped model is too eager to both allocate and throw away existing slots under contention instead lazily allocate and eventually reuse them, keeping them both stable and more cache-friendly for existing threads.
The existing shared size-class chunk cache degrade severely under heavy contention - and its algorithm is not really made to be effective under concurrent usage.
The chunk cache is not able to purge idle chunks if a specific size class end up allocating from the same magazine's current chunk, causing memory waste.

Modification:

  • Lifts the striped logic up, sharing it across a variety of allocation sizes, to better react to contention
  • Make local heaps lazily allocated and "stable" vs their stripe slot position
  • Exposed mpsc recyclers thanks to the new ownership model
  • Drop the shared size class chunk cache implementation
  • Recycle free lists (limited) and size-class chunks across "compatible" classes
  • Implemented per-class tick to drive purging, enabling recycling/deallocation of idle chunks

Result:

  • better scalability
  • (more) prompt release and reuse of memory across different size classes

Fixes #17028


Current state (head 1f303f3; replaces the earlier update notes)

Design. Heaps: one per stripe (one lock each) and one per event loop (thread-local, no lock), each with size-class magazines (now up to 132 KiB) and a recycler for the chunk buffers they give up. Buffers from 132 KiB to 1 MiB (buddy blocks) come from a large-buffer magazine of the same heap, so an event loop takes them from its own heap without a lock; they are the exception now. Releases from other threads leave a note that the owner applies on its slow paths.

Idle memory is bounded and given back. Every 10,000 allocations of a heap (size classes counted on their purge ticks, large buffers by their block size) the clock is read once; after 10 s a decay frees half, rounded up, of what stayed unused a whole interval: recycled buffers, idle large-buffer chunks, the large-buffer chunk in use once wholly free, and the chunks of a size class that allocated nothing (via the recycler). An event loop's large chunks so age with its own traffic, like its size classes. Nothing on the allocation or release fast paths. A heap that stops allocating keeps its memory until it is freed. At most, with the defaults, about 84 MiB per heap (32 MiB recycled, 32 MiB of idle large chunks, the chunk each size class and the large-buffer magazine allocate from), for every event loop that allocates and every stripe in use; on an event loop, chunks emptied by other threads' releases come under that bound when it applies their notes, on its next slow path or decay.

User-visible changes

io.netty.allocator.chunkPurgeInterval new name of chunkPurgePollsThreadLocal (still read, warns); default 4
recycledChunkBytes / chunkReuseQueueBytes new: per-heap bounds of recycled / idle large-buffer bytes (32 MiB each)
chunkReuseQueueCapacity, magazineBufferQueueCapacity now per stripe
chunkPurgePollsShared, chunkPurgeThreshold, threadLocalChunkCacheMaxBytes/MinBytes removed, warn when set
size classes up to 132 KiB (was 16.5 KiB): buffers of 17-132 KiB come from size-classed chunks
usedMemory(), JFR AllocateChunk/FreeChunk count a chunk buffer from the chunk allocator until it is given back, recycler included; allocated − freed = usedMemory()
io.netty.recycler.ratio no longer applies to the event loops' buffer-object pool
netty-common MpscIntQueue.capacity()/resetAndFill() (default methods), Recycler(int, boolean, boolean)

Results vs 4.2 (901d1c5; Ryzen 9 7950X, one NUMA node, 2300 MHz, JDK 21)

  • Mixed test (8 event loops + 16 platform threads, 1 GiB burst, released, then light traffic): memory held after 120 s 984 MiB on 4.2, 49 MiB with this PR (RSS above baseline 1062 vs 135 MiB); peak 1180 vs 1018 MiB. A heap that keeps allocating large buffers keeps the chunk it allocates from (up to 8 MiB) while it uses it.
  • Large buffers per event-loop heap instead of on the stripes (same change on an earlier base, fa21d4b, event-loop cells of the harness): latency geomean 1.02, peak RSS 1.00.
  • Allocation harness (published h2h harness, ADAPTIVE, 84 cells, 1 fork): latency geomean 0.203 of 4.2 (event loop 0.310, platform threads 0.133), peak RSS 0.421; worst cell 1.058 in latency; peak RSS higher in three small-live-set event-loop cells (1.11-1.16).
  • Head-to-head vs the Java mimalloc port: latency geomean 0.873, peak RSS 0.955 (cells, data).

Verified: common and buffer on JDK 11 (revapi, checkstyle) and with 1/2/4 processors; in low-memory mode only the two tests that already fail on 4.2 fail.

@franz1981

Copy link
Copy Markdown
Contributor Author

This closes #17047 and replace it.

@franz1981

Copy link
Copy Markdown
Contributor Author

052ce63 has introduced a tiny performance regression which I'm still investigating.

In the meantime I'm adding other changes to make naming and classes more clear.
I'll add them as separate commits.

In order to perform tests without chunk churning, I've added 6ab4716 too, which I'll send a separate PR as well FYI @chrisvest

@franz1981

Copy link
Copy Markdown
Contributor Author

I see that the current model on this pr would enable a minalloc style local release path which would benefit to prevent chunk churning and the artificial floor of 8M per size class cache which is applied to 4.2.
@laosijikaichele I think we have to rethink the cache management to look more like what minalloc does.
Any suggestion is welcome to keep a better balance between memory usage and chunk churning with many live buffers

@laosijikaichele

Copy link
Copy Markdown
Contributor

I see that the current model on this pr would enable a minalloc style local release path which would benefit to prevent chunk churning and the artificial floor of 8M per size class cache which is applied to 4.2.

@laosijikaichele I think we have to rethink the cache management to look more like what minalloc does.

Any suggestion is welcome to keep a better balance between memory usage and chunk churning with many live buffers

Thanks for reaching out. I'm currently away on vacation and will take a look once I'm back.

@franz1981

Copy link
Copy Markdown
Contributor Author

@laosijikaichele you can ignore the big amount of changes I have here, please: in the final version I plan to split into separate files the allocator key components too 🙏
This is using a mechanism very similar to mimalloc (withou biasing) - and notification-based, in order to avoid having floors/ceiling on the live set of allocations.
Is not as optimal as it should, because I've implement freelists recycling, not as simple as mimalloc does with recycled "blocks", but is quite effective as it is shared among many size-classes.

In any case this grant me a very very good performance for the event loop case, and the platform one, fixing some of the shortcomings of #17166

@franz1981

franz1981 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Just for myself: the epoch based mechanism on top of new striped model was impl at 191f507
while the changes we have so far move this to a notification based approach which remove the ceil of the size class chunk cache, allowing buffers releases to promptly made available or retire a chunk (into a shared recycling parking lot).
There are two reasons for this change:

  • if the ceil is too high, a cache retain too much memory, which requires further allocations of the same size to slowly purge them (back to the OS)
  • If the ceil is too small, it cause excessive OS malloc/free to respect the limit and still make purged chunks unable to further satisfy incoming allocations, in a vicious circle which cause other temporary fresh chunk allocations

In the new notification based model, instead, chunks will be allocated to serve the incoming requests and accomodate for the live required buffers, but, once released, will be made available or, if fully released, recycled in the shared parking lot, to serve future demand.
If a chunk is fully released and recycled in the parking lot but exceeding its capacity, it will be freed back to the OS.
That means that the total available cached memory is still bounded, but once a buffer is allocated it has the chance to be cached and reused as many time as required

@franz1981
franz1981 force-pushed the 4.2_chunk_recycling branch 3 times, most recently from 82bd38c to b41f062 Compare September 26, 2026 13:01
@franz1981
franz1981 requested review from chrisvest and normanmaurer and removed request for chrisvest September 28, 2026 09:21
@franz1981

franz1981 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@chrisvest @laosijikaichele I'm not fully convinced by fa21d4b (a large-buffer magazine per event-loop heap), and I'd like your opinion.

  • With size classes now up to 132 KiB, most allocations never reach the buddy path: large buffers are the exception.
  • Per heap, large-buffer memory scales with the number of event loops that ever allocate a large buffer, not with how many large buffers are live: each keeps at least one chunk (≥ 2 MiB, room for several buffers) while it uses them. In exchange there is no lock, and the idle chunks age with the event loop's own allocations.
  • Per stripe, event loops share the chunks, and the number of stripes only grows under lock contention, so with rare large buffers it stays small, and so does the footprint. The catch is the decay: an event loop counts its allocations toward its own heap, not the stripe, so the stripe's idle chunks need another signal, e.g. an event loop's decay also ageing the stripes it used.

The Java mimalloc port also has one heap per event loop, but cuts large blocks (≤ 2 MiB) from the same 4 MiB segments as the small pages, so a rare large buffer needs no dedicated memory; the price is a floor of one segment per heap. Giving memory back as uniform 4 MiB segments also suits glibc better than our mix of 128 KiB - 8 MiB chunks, which glibc keeps in its arenas after they are freed.

Options: keep it per heap, or go back to stripes plus the decay fix.

@laosijikaichele

Copy link
Copy Markdown
Contributor

@chrisvest @laosijikaichele I'm not fully convinced by fa21d4b (a large-buffer magazine per event-loop heap), and I'd like your opinion.

  • With size classes now up to 132 KiB, most allocations never reach the buddy path: large buffers are the exception.
  • Per heap, large-buffer memory scales with the number of event loops that ever allocate a large buffer, not with how many large buffers are live: each keeps at least one chunk (≥ 2 MiB, room for several buffers) while it uses them. In exchange there is no lock, and the idle chunks age with the event loop's own allocations.
  • Per stripe, event loops share the chunks, and the number of stripes only grows under lock contention, so with rare large buffers it stays small, and so does the footprint. The catch is the decay: an event loop counts its allocations toward its own heap, not the stripe, so the stripe's idle chunks need another signal, e.g. an event loop's decay also ageing the stripes it used.

The Java mimalloc port also has one heap per event loop, but cuts large blocks (≤ 2 MiB) from the same 4 MiB segments as the small pages, so a rare large buffer needs no dedicated memory; the price is a floor of one segment per heap. Giving memory back as uniform 4 MiB segments also suits glibc better than our mix of 128 KiB - 8 MiB chunks, which glibc keeps in its arenas after they are freed.

Options: keep it per heap, or go back to stripes plus the decay fix.

@franz1981 Given that large-buffer allocation is likely not the common use case, I'd prefer the per stripe design.
AFAIK the native mimalloc(version 3) is moving the same way: v3 "simplifies the lock-free design of previous versions and improves sharing of memory between threads. On certain large workloads this version may use (much) less memory.", dropping v2's per-thread segment layer in favor of arenas shared across threads.

@franz1981

Copy link
Copy Markdown
Contributor Author

@laosijikaichele agreed, thanks. d33cd10 takes the buffers above the size classes from the stripes again. To keep their idle chunks aging when only event loops use them, an event loop's decay now also decays every stripe in use whose last decay is at least an interval old, when its lock is free: a stripe still decays at most once per interval, and nothing is added to the allocation or release paths.

A heap's SizeClassChunkRecycler kept up to recycledChunkBytes of chunk buffers
for as long as the heap lived, however long nobody took them. Every 10,000
allocations of the heap it now looks at the clock once, and when 10 s passed
since its last decay it frees half, rounded up once over all its pools, of the
buffers that sat unused through the whole interval, oldest first; otherwise it
waits for the next count. The count is carried by the heap's purge ticks, which
add the allocations they counted, so there is no cost per allocation and one
clock read per count. A per-pool low-water mark finds the cold buffers, and
nothing is allocated on the way (measured: 0 bytes over 1M ticks and repeated
decays; one decay freeing 128 buffers of 128 KiB takes about 25 us, unpinned
CPU, rough). Tests pin the halving, the oldest-first order with free lists kept
paired, the low-water mark, both gates and the restart of the count, the single
rounding, and the heap's own ticks driving it.
The wholly free chunks a stripe keeps for buffers above the size classes, up
to chunkReuseQueueBytes, were never given back while the stripe lived, and
those allocations counted toward nothing. The decay's gate moves into a
per-heap IdleDecay, fed by the size-class purge ticks as before and by the
large-buffer magazine's slow path, which counts one: a slow path is at least
one allocation and may be exactly one, so counting more could age the stripe
faster than its allocations do, and no fast path counts anything. When it
fires it ages the recycler as before and, on a stripe, frees half, rounded up,
of the chunks that stayed wholly free through the whole interval, oldest
first. Each chunk is stamped with the decay count when it is filed wholly
free, which is exact where a low-water mark would not be, since chunks leave
that list by fit. Tests pin the halving, a chunk idle for part of an interval
surviving it, the active chunk never counting as idle, one count per slow path
and none on the fast path, and a slow path driving a decay end to end.
idleChunksAreEvictedAfterRelease sized its burst from chunkReuseQueueCapacity,
twice the processors: on a 4-core CI runner the burst fit in the heap's
chunk recycler, which usedMemory() counts, so nothing was freed and the test
failed. The burst is now twice the recycler's budget, and the settled memory
is bounded by that budget. The seeded trace's recorded memory keeps three
idle large-buffer chunks, which one processor does not allow: it now assumes
at least three. The buffer tests pass with -XX:ActiveProcessorCount 1, 2, 4
and 64.
…classes

An event loop took its buffers above the size classes from a stripe, under
the stripe's lock, although it has a heap of its own for everything else.
The stripe's idle decay then only counted those allocations' slow paths,
so the wholly free chunks a burst left there were never given back (32 MiB
kept for four minutes of steady traffic in a burst-then-quiet test), while
the event loop's own heap, busy with small allocations, aged only its
recycler.

A thread-local heap now creates a BuddyMagazine on its first such buffer,
touched only by its owner thread: the owner puts released blocks straight
back, any other thread leaves a note, as on a stripe whose lock is busy.
Since every other thread's release is a note there, the heap's size-class
slow path applies the magazine's notes too, so its idle bound holds without
waiting for a large allocation. The heap's IdleDecay ages the magazine with
the recycler, fed by all of the thread's allocations, and applies the notes
first. The magazine is freed with the heap, and its buffers report
thread-local chunks to JFR. Stripes keep theirs for the threads without a
heap. Each event loop can now keep up to chunkReuseQueueBytes of idle large
chunks plus its active one, where the stripes' bound was shared.
After a burst, every size class a heap ever used kept its current chunk and
the one chunk of its retention floor for good, whether or not it still
allocated: in a mixed test, after 120 s of steady 1-16 KiB traffic, 147 MiB
of 390 MiB held sat in the size classes that traffic never used, on every
heap. And once the recycler and the idle large-buffer chunks were empty, the
decay no longer looked at the clock at all.

At each decay a size class that made no allocation since the previous one,
read from the counters its allocations already keep, gives up its current
chunk and every wholly free chunk it keeps, the floor included, to the
heap's recycler, which gives them back from the next decay on, by halves,
like any buffer offered to it. While the recycler has no room they stay with
the class, so memory only goes back by halves. The floor stays for a class
in use; chunks with buffers out stay. Every count of 10,000 allocations now
looks at the clock, as the rule says.
Each heap kept the chunk its large-buffer magazine allocates from for good,
since only chunks filed on its queues age; in a mixed test that was one
8 MiB chunk per heap, 192 MiB of 390 MiB held after 120 s of traffic that
allocated no large buffer.

At a decay, after applying the notes, a wholly free active chunk is filed
like any other chunk while the idle chunks have room for it: it is idle from
that decay on and given back once it stays so through the whole next
interval, while the next allocation polls it back on its slow path. A chunk
with a buffer out stays active, and so does one the idle bound has no room
for, rather than being freed before any interval.
…et Recycler

MpscIntQueue is a public interface, and this PR added two abstract methods
to it, capacity() and resetAndFill(int, int), with revapi told to ignore
the break. Code implementing the interface outside Netty would no longer
compile. Both are now default methods that throw
UnsupportedOperationException, overridden by the queue create() returns,
and the revapi ignores are gone.

The Recycler constructor with an exclusiveGet flag had no documentation
and silently ignored the flag for a guarded pool. It now says what it is
for, a pool whose get() only one thread at a time calls, and rejects the
flag without unguarded.
Low-memory mode pools the size classes up to 16896 only, pools no buffer
above them and has no thread-local heaps. Several tests this PR added
assumed otherwise: they failed there, one leaked the buffer it allocated
before its assumption skipped it, and a JFR test waited forever for an
event low-memory mode never fires, hanging the test JVM. They are skipped
in low-memory mode now, the skipped test releases its buffer first, and
the JFR test's waits are bounded. What still fails in low-memory mode
fails on 4.2 as well (shouldReuseChunks,
adaptiveJfrBufferAllocationThreadLocal).
A review of the whole change found comments that no longer matched the
code or cited internal benchmarks, and two corner cases:

- The idle bound is per heap, and a stripe holds a large-buffer magazine
  too. A decay frees half of what stayed idle a whole interval, never more,
  and the IdleDecay documentation now states what a heap can keep idle at
  most (about 84 MiB per heap with the defaults), which it did not before.
- Benchmark names and an unsourced JIT claim are dropped from comments.
- The recycler's room check adds in long, so a budget close to
  Integer.MAX_VALUE cannot overflow it, and evicting an idle size class's
  chunks no longer assumes a recycler exists.
- The JFR chunk events describe what they now mean: memory taken from, and
  given back to, the memory the allocator is built on.
- The stripes' buffer-object pool uses MpscArrayQueue, whose index fields
  native images need registered, as the other JCTools queues' are.
- The seeded trace test documents what it pins instead of how it got
  there, and is skipped if it ever runs longer than a decay interval.
…vent loops age them

This reverts the magazine for buffers above the size classes that every
thread-local heap had (fa21d4b). With the size classes going up to
132 KiB such buffers are the exception, and one magazine per event loop
made their memory grow with the number of event loops that ever allocate
one, each keeping a chunk of at least 2 MiB while it uses them, instead of
with how many are live; on the stripes the event loops share chunks, and
the number of stripes only grows under lock contention.

What the per-heap magazine gave for free was the decay: an event loop
counts its allocations on its own heap, so a stripe that only event loops
use for large buffers never counted enough to decay its idle chunks. A
thread-local heap's decay now also decays every stripe in use whose last
decay is at least an interval old, when its lock is free: a stripe still
decays at most once per interval, by the same rule, and nothing is added
to any allocation or release path.
A stripe that event loops use for buffers above the size classes only
counted those allocations' slow paths toward its decay, one each: after a
burst the chunk it allocates from serves them all, so the count never got
anywhere and the stripe's idle large chunks were never given back. The
previous commit had event loops' decays sweep the stripes instead, which
puts one heap's upkeep on another heap's thread.

The large-buffer magazine now counts every allocation, on the fast path as
on the slow one, with its block size in units of the smallest size class:
a large buffer paces the stripe's clock reads like the small buffers its
bytes would make. It runs under the stripe lock that path already holds.
The count only decides how often the clock is read: a stripe still decays
at most once per interval, freeing half of what stayed idle through it.
The sweep is removed.
…classes

An event loop took its buffers above the size classes from a stripe. Each
of those allocations counts toward that stripe's decay (546e922), which
ages a stripe only while some thread allocates large buffers on it: the
chunks an event loop's burst left on a stripe no thread allocates large
buffers on again stay there, since only a heap's own allocations may age
it. In a burst-then-quiet test (8 event loops and 16 other threads, a
1 GiB burst of all sizes, released, then light traffic of small buffers)
the allocator still held 187 MiB after two minutes, 148 MiB of it such
chunks; with this change it holds 49 MiB.

A thread-local heap now creates a BuddyMagazine on its first such buffer,
touched only by its owner thread: the owner puts released blocks straight
back, any other thread leaves a note, as on a stripe whose lock is busy.
Since every other thread's release is a note there, the heap's size-class
slow path applies the magazine's notes too, and the heap's IdleDecay
applies them before it ages the magazine with the recycler, fed by all of
the thread's allocations, each large one by its block size. The magazine is
freed with the heap, and its chunks are reported to JFR as thread-local.
Stripes keep theirs for the threads without a heap.

Costs: each event loop that allocates large buffers keeps its own chunk
and up to chunkReuseQueueBytes of idle ones, where event loops shared the
stripes'; they age with the loop's own allocations. The chunks other
threads' releases empty come under that bound when the owner applies the
notes, on its next slow path or decay. Per buffer: an allocation above the
size classes looks for a thread-local heap first, as the size classes do;
a large release on a stripe reads the magazine's owner; the size-class
slow path, once per chunk's worth of allocations, reads the large
magazine's notes.

This undoes d33cd10.
@franz1981
franz1981 force-pushed the 4.2_chunk_recycling branch from d6e63da to 0b05f0f Compare October 12, 2026 12:08
…hunk objects

Recycler: the exclusive-get pool honours io.netty.recycler.blocking, and both
new constructors carry the unguarded disclaimer.

BuddyTree becomes a top-level class and takes its minimum block size from the
allocator: the smallest power of two above the largest size class (132 KiB),
so 256 KiB. Nothing below that is ever claimed, so the trees lose three
unused levels and the buddy free lists shrink to match.

The allocator's javadoc names the generational hypothesis; the chunk events'
descriptions say when they fire; @VisibleForTesting replaces the comments
(buffer now declares the provided org.jetbrains:annotations dependency that
common already uses).

A SizeClassedChunk object is made for one magazine and stays with it,
serving one buffer at a time. When every segment is back, the owner side
retires the chunk: the buffer goes to the heap's recycler (or back to the
chunk allocator), and the object waits on its cache's spare list. The next
chunk the magazine needs takes a spare object, or makes one, and a recycled
buffer, or allocates one; takeBuffer sets only what belongs to the buffer.
The two free lists are built once, when the object is, and are never
refilled or reset: when a buffer is given up every offset is on one of them,
and the next buffer is handed out from them as they are. A chunk rebuilt
from a recycled buffer therefore allocates nothing.

A thread releasing a segment of the previous buffer that is still between
its offer and its read of the state is counted by the queue before the chunk
can read as wholly free; its value lands in the slot it claimed, and the
owner's poll waits for it there. The reset that could have overwritten such
a slot is gone, and with it the PR's additions to MpscIntQueue: it and its
test are upstream's again.

The recycler pools buffers only. IntStack is built from a capacity, a count
and an IntUnaryOperator, and loses refill. A size class that stayed idle
through a decay interval lets go of its spare objects together with its
chunks, as does a dying cache; chunks of a dead cache are never reused.

Tests: the JIT regression test for the old BuddyTree constructor loop goes
with the loop; the seeded trace compares the stripe with the thread-local heap
and checks a documented bound instead of a golden table; threads started by
tests hand their failures back through CompletableFutures; the recycler test
deals in buffers; the cache test expects a given-up chunk on the spare list
and mocks retire.
A thread-local chunk object that takes a new buffer drains its external
free list into its local stack first, so the segments other threads gave
back to the previous buffer are handed out by pop again, as from a new
chunk. The drain stops at a slot a releaser claimed but has not written
yet, which stays queued for a later poll: nothing waits. IntStack is the
drain's IntConsumer.

retire asserts the chunk is still AVAILABLE (never after its cache died),
and the releaser's comment on a non-AVAILABLE state names the spare list.
idleChunksAreEvictedAfterRelease fills its chunks with 16 KiB buffers
instead of 256-byte ones, and chunksAreReusedAcrossSizeClasses frees 4
chunks instead of 64: the same chunks past the recycler budget, and the
same reuse, with far fewer buffers alive at once. Each tracked buffer
keeps its stack traces, and two of these bursts running concurrently
filled a 4 GB test heap.
@franz1981

franz1981 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor Author

@chrisvest 6f52f79 addresses your review (plus reusing size-classed chunk objects), and 570b197 starts a reused thread-local chunk from its stack. e47ed40 is tests only: two recycler tests held ~260k leak-tracked buffers each and ran the leak-detection legs out of heap, so they now overflow the recycler with bigger buffers. The musl-verify failures are unrelated (two netty-codec-native-quic versions on the classpath), as on other 4.2 PRs.

* is the smallest block the buddy path is ever asked for, since every request up to that class is a segment.
*/
static final int BUDDY_MIN_BLOCK_SIZE =
MathUtil.safeFindNextPositivePowerOfTwo(SIZE_CLASSES[SIZE_CLASSES_COUNT - 1] + 1);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider moving this below the POOLED_SIZE_CLASSES_COUNT definition, and making use of it so we automatically take IS_LOW_MEM into account.

this.chunkController = strategy.createController(allocator);
this.chunkCache = strategy.createChunkCache(chunkRecycler, sizeClassIndex, stripeLock);
this.purgeTickThreshold = (int) Math.min(Integer.MAX_VALUE,
CHUNK_PURGE_INTERVAL * (strategy.chunkSize / strategy.segmentSize));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use checked multiplication, to prevent overflow. Or clamp CHUNK_PURGE_INTERVAL.

Object chunkA = anyChunkOf(bufs.get(0));
Object chunkB = anyChunkOf(bufs.get(perChunk));
Object chunkC = anyChunkOf(bufs.get(2 * perChunk));
assumeTrue(chunkA != chunkB && chunkB != chunkC, "one chunk per " + perChunk + " buffers");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you mean assertTrue? You'll need to release all the bufs if you mean to assume and this assumption doesn't hold.

BuddyHeld b = new BuddyHeld();
b.held.add(allocator.heapBuffer(BUDDY_NOTE_SIZE, BUDDY_NOTE_SIZE));
b.perChunk = (int) (allocator.usedHeapMemory() / BUDDY_NOTE_SIZE);
assumeTrue(b.perChunk >= 2, "a buddy chunk holds " + b.perChunk + " buffers");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assume or assert? You'll need to release the b.held buffers if this is an assumption and it doesn't hold.

…urge interval, and assert test preconditions

Motivation:

Review: the buddy tree's minimum block ignored low-memory mode, the purge
tick threshold could overflow for a very large purge interval, and two
tests assumed what they should assert, leaking their buffers when the
assumption failed.

Modifications:

- BUDDY_MIN_BLOCK_SIZE is the next power of two above the largest pooled
  size class.
- CHUNK_PURGE_INTERVAL is clamped to Integer.MAX_VALUE.
- The two tests fail, after releasing what they hold, when a chunk does
  not hold the buffers they expect.

Result:

Review comments addressed.
@franz1981

Copy link
Copy Markdown
Contributor Author

@chrisvest Addressed in 85ba70d.

@testlens-app

testlens-app Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

🚨 All tests passed but jobs failed 🚨

Failed Jobs without Test Failures

❌ Verify native library loading on musl / musl-verify-alpine-aarch64-gcompat
❌ Verify native library loading on musl / musl-verify-alpine-aarch64
❌ Verify native library loading on musl / musl-verify-alpine-x86_64-gcompat
❌ Verify native library loading on musl / musl-verify-alpine-x86_64
❌ Verify native library loading on musl / musl-verify-glibc-control-x86_64

🏷️ Commit: 85ba70d
▶️ Tests: 125969 executed
⚪️ Checks: 26/26 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

@chrisvest

Copy link
Copy Markdown
Member

Code looks good, but the AllocationPatternSimulator is showing a regression on the e-commerce.jfr pattern, though.

4.2 memory usage chart image
This PR memory usage chart image

@franz1981

franz1981 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Checking, so far i've run the ecommerce workload using the @laosijikaichele benchmark in JMH which have no timing (sleeps basically), never run this one in this form!
@chrisvest did you checked in the others you care bud?

@franz1981

franz1981 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@laosijikaichele Accordly to Claude both my PR, the page store branch and mimalloc fail badly with this test

┌──────┬─────────┬─────────┬────────────┬───────────────┐
│ live │   4.2   │   PR    │ page store │ mimalloc Java │
├──────┼─────────┼─────────┼────────────┼───────────────┤
│ 128  │ 11.5 MB │ 27.7 MB │ 37.8 MB    │ 37.4 MB       │
├──────┼─────────┼─────────┼────────────┼───────────────┤
│ 512  │ 23.2    │ 36.7    │ 49.5       │ 50.3          │
├──────┼─────────┼─────────┼────────────┼───────────────┤
│ 1024 │ 31.5    │ 48.8    │ 62.3       │ 67.1          │
└──────┴─────────┴─────────┴────────────┴───────────────┘

I'm checking what the test actually....test. And why we get better latencies compared to 4.2 with much worse used memory; my educated guess is that we churn way more in 4.2...let's see
Feel free to try the Chris simulator as well

@franz1981

franz1981 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@chrisvest Reproduced: 11.5 → 27.7 MB at 128 live, same live bytes. Two causes, from heap dumps:

  1. The stripe count doubles on the first lock collision and never shrinks, so the 4 threads end up on 4 stripes, each keeping one chunk per size class (64 chunks vs 4.2's 19). Expanding only after repeated collisions keeps it at 2 stripes: 27.7 → 15.5 MB.
  2. The six new size classes (32 KiB–132 KiB) keep 20 chunks of 512 KiB for 1.5 MB live, plus one empty 2 MiB buddy chunk per stripe for the rare larger buffers: +12 MB, on event-loop threads too.

With both changed as an experiment, memory at 128 live is 11.4 MB on plain threads (4.2: 11.5) and 17.6 MB on event-loop threads (4.2: 19.3); at 1024 live it stays 4–6 MB above 4.2, which is wholly-free buddy chunks kept for reuse. In exchange the PR makes no one-shot allocations, where 4.2 allocates up to ~1,200 unpooled 64 KiB chunks per 2 min at 1024 live.

I think these applies to mimalloc too @laosijikaichele

@chrisvest

Copy link
Copy Markdown
Member

Do the other benchmarks still look reasonable with those changes?

@franz1981

Copy link
Copy Markdown
Contributor Author

@chrisvest Which ones do you mean: the other profiles in netty-allocator-profiles through the simulator, or the throughput/latency runs (lao's harness, the #17485 cells)? The two changes in my last comment are experiments to isolate the causes, not a proposal yet; the six classes in particular came from the #17485 latency results, so dropping them is not on the table yet.

@chrisvest

Copy link
Copy Markdown
Member

@franz1981 Ok. I was thinking of Lao's harness.

@franz1981

franz1981 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@chrisvest @laosijikaichele findings so far.

The regression is the stripe expansion rule: the PR doubles the number of stripes on the first scan that finds every
stripe in reach locked, and one plain lock collision is enough.

Your simulator, 4 threads at 1 alloc/ms, head 85ba70d (one scan length for all size classes):

len = 1
T0: alloc 32B  -> S0, lock OK, create the 32B magazine + chunk on S0
T1: alloc 32B  -> S0 locked (T0 still inside), round 2 locked -> expand: len = 2 -> S1, create 32B magazine + chunk
T2: alloc 32B  -> S0, S1 locked -> expand: len = 4 -> S2, create
T3:            -> S3, create
... from now on every thread allocates every class on its own stripe: 4 stripes x 20 classes = 80 current chunks
(21 MB) where 4.2 keeps one magazine per class group, plus the few groups that doubled.

4.2, same run: each size class has its own magazine array with its own lock, starting at one magazine.

T0: alloc 32B -> M0 of the 32B group, lock OK
T1: alloc 32B -> M0 locked -> tries again, M0 is free -> allocates
                (rarely the retry fails too: then only the 32B group doubles, one more chunk)

Why 4.2 ends up with far fewer chunks: (1) a doubling costs 4.2 one magazine and one chunk of one class, while the
PR adds a magazine and a chunk of every class on the new stripe, because stripes and the scan length are shared by
all classes; (2) 4.2's locks are per class, so threads collide only when they allocate the same class at the same
moment, while the PR's stripe lock collects the collisions of every class, so the PR doubles sooner.

In short: a few collisions in the first milliseconds double the stripes three times, and from then on every thread
keeps a magazine of every size class on its own stripe, four times the chunks of 4.2.

Tried: one scan length per size class. It fixes the simulator, but lao's harness on E_COMMERCE (32 platform
threads, 32768 live buffers) shows a latency regression of 7-13%.

The model: a stripe is one lock plus one magazine per size class. Thread t starts its scan for class c at stripe
t & (len[c] - 1) and tries the other stripes within len[c] if that one is locked; a scan where all of them are locked
doubles len[c] only. The lock it takes is still the stripe's, shared by every class of that stripe. Same trace:

len[32B] = 1, len[512B] = 1, len[8KiB] = 1, ...        // one length per class
T0: alloc 32B  -> S0, create the 32B magazine on S0
T1: alloc 32B  -> S0 locked, round 2 locked -> expand 32B only: len[32B] = 2 -> S1, create
T2, T3: same   -> len[32B] = 4, 32B magazines on S2, S3; every other class still at 1
T1: alloc 512B -> len[512B] = 1 -> S0, T0's home stripe; T2, T3 -> S0 as well
... 32 threads, steady state: the hot classes reach 32 (T21 -> S21), a rare class stops at 16
(T5 -> S5, T21 -> S21 & 15 = S5): it would widen only if all 16 stripes were locked in one scan, never.
So T21 allocates most classes on S21 and the rare ones on S5, under T5's lock.

The per-class lengths recover the e-commerce footprint in your simulator but regress latency in lao's case for two
reasons:

  1. Each heap a thread has to reach for one of its size classes adds that heap's metadata to its cache occupancy:
    19.4 distinct stripes per thread instead of 4.2, and the extra misses refill from the thread's own L2
    (fill-source counters, +3 per allocation, same at 128 live). This is both by design (the start stripe differs per
    class) and from contention: a failed lock sends the thread into heaps it would otherwise never use.
  2. A size class widens only when a scan finds all of its stripes locked, so a rarely allocated class widens slowly
    or never. Its allocations keep landing on stripes that other threads use as home for everything they allocate,
    and each landing is a collision or a hop to the next stripe. With one shared length every thread ends up alone on
    its stripe at saturation and this does not happen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AdaptivePoolingAllocator: Performance gap in latency/RSS in several benchmark cases compared with other allocators

3 participants