GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Make AdaptiveByteBuf.memoryAddress() faster by lhotari · Pull Request #17767 · netty/netty

Conversation

@lhotari

@lhotari lhotari commented Oct 5, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Motivation:

An AdaptiveByteBuf is a segment of a chunk's root buffer. AdaptiveByteBuf._memoryAddress() computes its address by calling the root buffer's _memoryAddress() and adding the segment's offset. On every call, the root buffer's _memoryAddress():

  1. checks isAccessible(),
  2. calls hasMemoryAddress(),
  3. calls memoryAddress(), which checks the reference count again in ensureAccessible().

These checks on the root buffer are redundant. The root buffer stays accessible while the AdaptiveByteBuf holds a segment of its chunk, and the root buffer's address doesn't change.

A gathering write in the native transports gets the memory address of each buffer that it writes (IovArray.add()). In a profile of an Apache Pulsar broker writing 8 KB messages, the checks on the root buffer were 3.3 % of the I/O threads' CPU.

Modification:

Existing behavior that this relies on:

  • The address of an AdaptiveByteBuf is the root buffer's address plus the segment's offset in the chunk (startIndex).
  • The allocator calls AdaptiveByteBuf.init() when it hands out a buffer. When a buffer grows beyond its segment, the reallocation moves it to a new segment and calls init() again.

Changes:

  • Chunk computes the root buffer's memory address once, when the chunk is created.
  • AdaptiveByteBuf.init() stores the buffer's memory address, the root buffer's address plus startIndex, in a new field. When the root buffer has no memory address, it stores 0, as AbstractByteBuf._memoryAddress() returns for buffers without one.
  • AdaptiveByteBuf._memoryAddress() returns the field, instead of calling the root buffer's _memoryAddress(). The public memoryAddress() still checks that the AdaptiveByteBuf itself is accessible, and, since Throw UnsupportedOperationException from AdaptiveByteBuf.memoryAddress() without an address #17820, throws UnsupportedOperationException when it has no memory address.
  • deallocate() resets the field, so _memoryAddress() still returns 0 after the buffer is deallocated.
  • A new test in AdaptiveByteBufAllocatorTest, testDirectBufferMemoryAddressFollowsItsSegment, allocates two direct buffers, so that the second one is likely at an offset above zero in the chunk. It compares each buffer's memoryAddress() with the address of the NIO buffer of the same range, which is computed from the chunk's buffer separately. It compares again after a buffer grows into another segment, and checks that _memoryAddress() returns 0 after release. AbstractByteBufTest.testMemoryAddressUnsupportedWhenNoMemoryAddress (Throw UnsupportedOperationException from AdaptiveByteBuf.memoryAddress() without an address #17820) covers the heap buffers.
  • A new benchmark, AdaptiveByteBufMemoryAddressBenchmark, gets the memory addresses of 16 direct buffers, as a gathering write does.

Result:

Each memoryAddress() call checks a reference count once, the AdaptiveByteBuf's own, instead of three times. The root buffer's address is computed once per chunk; allocating and releasing a buffer each add one field write.

AdaptiveByteBufMemoryAddressBenchmark with 16 buffers of 8 KB, on an Intel i9-9980HK at a fixed 2.4 GHz, with Unsafe enabled (-Dio.netty.noUnsafe=false), 2 alternating runs per side. Before is 4.2 at 60d9baf with only the benchmark added:

Before After
JDK 21, run 1, ops/s 18,497,697 ± 74,560 30,904,677 ± 69,876
JDK 21, run 2, ops/s 18,514,434 ± 31,468 30,915,307 ± 74,873
JDK 25, run 1, ops/s 18,532,696 ± 50,826 30,851,633 ± 296,462
JDK 25, run 2, ops/s 18,558,233 ± 23,243 30,877,691 ± 173,624

That's 3.38 ns per buffer before and 2.02 ns after on both JDKs: 67 % more throughput, with warm caches and a monomorphic call site.

JMH output
Benchmark                                            (buffers)  (size)   Mode  Cnt         Score       Error  Units

JDK 21 before:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18497696.574 ± 74560.210  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18514434.341 ± 31467.599  ops/s

JDK 21 after:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30904677.380 ± 69875.648  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30915306.886 ± 74873.233  ops/s

JDK 25 before:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18532696.343 ± 50826.312  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18558232.849 ± 23243.203  ops/s

JDK 25 after:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30851632.966 ± 296461.862  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30877691.180 ± 173623.904  ops/s

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@lhotari
Make AdaptiveByteBuf.memoryAddress() faster
cf4b699
Motivation:

An AdaptiveByteBuf is a segment of a chunk's root buffer.
AdaptiveByteBuf._memoryAddress() computed its address by calling the root
buffer's _memoryAddress() and adding the segment's offset. On every call,
the root buffer's _memoryAddress() checks isAccessible(), calls
hasMemoryAddress(), and calls memoryAddress(), which checks the reference
count again in ensureAccessible(). These checks on the root buffer are
redundant: the root buffer stays accessible while the AdaptiveByteBuf
holds a segment of its chunk, and the root buffer's address doesn't
change.

A gathering write in the native transports gets the memory address of each
buffer that it writes (IovArray.add()). In a profile of an Apache Pulsar
broker writing 8 KB messages, the checks on the root buffer were 3.3 % of
the I/O threads' CPU.

Also, when the root buffer has no memory address, such as a heap chunk,
memoryAddress() and _memoryAddress() returned the segment's offset in the
chunk, which isn't an address.

Modification:

- Chunk computes the root buffer's memory address once, when the chunk is
  created.
- AdaptiveByteBuf.init() stores the buffer's memory address, the root
  buffer's address plus startIndex, in a new field. When the root buffer
  has no memory address, it stores 0, as AbstractByteBuf._memoryAddress()
  returns for buffers without one. A reallocation calls init() again.
- AdaptiveByteBuf._memoryAddress() returns the field, instead of calling
  the root buffer's _memoryAddress(). The public memoryAddress() still
  checks that the AdaptiveByteBuf itself is accessible.
- deallocate() resets the field, so _memoryAddress() still returns 0 after
  the buffer is deallocated.
- AdaptiveByteBufAllocatorTest checks a direct buffer's memoryAddress()
  against the address of its NIO buffer, also after the buffer grows into
  another segment, and that a heap buffer's memoryAddress() is 0.
- AdaptiveByteBufMemoryAddressBenchmark gets the memory addresses of 16
  direct buffers, as a gathering write does.

Result:

Each memoryAddress() call checks a reference count once, the
AdaptiveByteBuf's own, instead of three times, and an AdaptiveByteBuf
without a memory address returns 0 instead of its offset. With 16 buffers
of 8 KB, AdaptiveByteBufMemoryAddressBenchmark gets 75 % more throughput:
3.06 ns per buffer before and 1.75 ns after.
@franz1981

franz1981 commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Re

A gathering write in the native transports gets the memory address of each buffer that it writes (IovArray.add()). In a profile of an Apache Pulsar broker writing 8 KB messages, the checks on the root buffer were 3.3 % of the I/O threads' CPU.

Let me challenge/stress this.
I believe the reason why you could have seen these accessibility checks in the wild (Apache Pulasar) is because you haven't enabled proper "plain load" accessiblity checks i.e. having Unsafe or VarHandle available.
Without these available you'll end up performing a volatile load of the ref cnt value which clearly have impact on surrounding other accesses due to the JMM.

So, very important, did you make sure Unsafe or VarHandle are properly used?
If not, can you verify the impact of having such available?

That said, I'm happy if we can save work to happen 🚀

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari

lhotari commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

So, very important, did you make sure Unsafe or VarHandle are properly used?

@franz1981 Good question. I went back to the JFR recording (combined recording of async-profiler (cpu 10ms interval) + JFR + jonoffcpu for off-cpu profiling with eBPF) of that profile to check. Unsafe was available.

The broker ran on JDK 25 (25.0.4.1) with --sun-misc-unsafe-memory-access=allow and the usual --add-opens flags for java.nio and jdk.internal.misc, and nothing that would disable Unsafe. All RefCnt frames in the profile are RefCnt$UnsafeRefCnt, so isLiveNonVolatile() was the plain PlatformDependent.getInt() and it was inlined.

Relevant JVM options from the recording
-Dio.netty.leakDetection.level=disabled
-Dio.netty.recycler.maxCapacityPerThread=4096
-Dio.netty.allocator.maxOrder=10
-Dio.netty.allocator.type=adaptive
-Dio.netty.tryReflectionSetAccessible=true
--sun-misc-unsafe-memory-access=allow
--add-opens=java.base/java.nio=ALL-UNNAMED
--add-opens=java.base/jdk.internal.misc=ALL-UNNAMED
--enable-native-access=ALL-UNNAMED
-XX:+UseZGC
-XX:+UseCompactObjectHeaders

In that profile (8 KB messages, 8 I/O threads), AdaptiveByteBuf.memoryAddress() was 4.2 % of the I/O threads' CPU samples. 3.5 % was in the root buffer's isAccessible() → RefCnt.isLiveNonVolatile() and 0.5 % in its ensureAccessible(). Most of it comes from single-buffer socket writes, and the rest from checksumming published messages through the buffer's address.

The most common stack (2.1 % of the I/O threads' CPU samples)
at io.netty.util.internal.PlatformDependent0.getInt  (inlined)
at io.netty.util.internal.PlatformDependent.getInt  (inlined)
at io.netty.util.internal.RefCnt$UnsafeRefCnt.isLiveNonVolatile  (inlined)
at io.netty.util.internal.RefCnt.isLiveNonVolatile  (inlined)
at io.netty.buffer.AbstractReferenceCountedByteBuf.isAccessible  (inlined)
at io.netty.buffer.AbstractByteBuf._memoryAddress  (inlined)
at io.netty.buffer.AdaptivePoolingAllocator$AdaptiveByteBuf._memoryAddress  (inlined)
at io.netty.buffer.AdaptivePoolingAllocator$AdaptiveByteBuf.memoryAddress  (inlined)
at io.netty.channel.epoll.AbstractEpollChannel.doWriteBytes  (inlined)
at io.netty.channel.epoll.AbstractEpollStreamChannel.writeBytes  (inlined)
at io.netty.channel.epoll.AbstractEpollStreamChannel.doWriteSingle  (inlined)
at io.netty.channel.epoll.AbstractEpollStreamChannel.doWrite  (inlined)
at io.netty.channel.AbstractChannel$AbstractUnsafe.flush0  (inlined)
at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe.flush0  (inlined)
at io.netty.channel.AbstractChannel$AbstractUnsafe.flush  (inlined)
at io.netty.channel.DefaultChannelPipeline$HeadContext.flush  (inlined)
at io.netty.channel.AbstractChannelHandlerContext.flush
at io.netty.handler.flush.FlushConsolidationHandler$1.run  (inlined)
at io.netty.util.concurrent.PromiseTask.runTask  (inlined)
at io.netty.util.concurrent.PromiseTask.run
at io.netty.util.concurrent.AbstractEventExecutor.runTask  (inlined)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute  (inlined)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks
at io.netty.channel.SingleThreadIoEventLoop.run
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run
at io.netty.util.internal.ThreadExecutorMap$2.run
at io.netty.util.concurrent.FastThreadLocalRunnable.run
at java.lang.Thread.runWith
at java.lang.Thread.run

For context, this was tested on a rather old CPU: a 2019 Dell XPS 15 7590 laptop with an Intel Core i9-9980HK (8 cores, 16 threads). The broker profile comes from the Pulsar Performance Testing Framework, which runs the Pulsar cluster and its clients in Docker, here on Linux (Pop!_OS 24.04, kernel 7.1.5). To reduce variance between test runs, the framework can control the power-saving settings and fix the CPUs at 2.4 GHz, with no turbo boost. The JMH benchmark in this PR ran with the same settings.

franz1981 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer

normanmaurer commented Oct 14, 2026

Copy link
Copy Markdown
Member

So @lhotari you are still thinking this is worthwhile correct ?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari

lhotari commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

So @lhotari you are still thinking this is worthwhile correct ?

@normanmaurer yes, I think that this change is a useful performance improvement.

normanmaurer reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer
normanmaurer requested review from chrisvest and franz1981 October 14, 2026 19:52
@normanmaurer normanmaurer added this to the 4.2.20.Final milestone Oct 14, 2026
normanmaurer
normanmaurer approved these changes Oct 14, 2026
View reviewed changes
chrisvest
chrisvest reviewed Oct 14, 2026
View reviewed changes
Comment thread buffer/src/test/java/io/netty/buffer/AdaptiveByteBufAllocatorTest.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

franz1981
franz1981 approved these changes Oct 15, 2026
View reviewed changes

@franz1981 franz1981 left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Lgtm

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
lhotari added 2 commits October 15, 2026 16:48
@lhotari
Merge remote-tracking branch 'origin/4.2' into lh-adaptive-memory-add…
adf84d5
…ress

# Conflicts:
#	buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java
@lhotari
Remove the test of a heap AdaptiveByteBuf's memory address
bc01fbc
Motivation:

AbstractByteBufTest.testMemoryAddressUnsupportedWhenNoMemoryAddress (netty#17820) checks that
memoryAddress() throws for a buffer without a memory address, which covers the heap buffers of the
adaptive allocator. testHeapBufferMemoryAddressIsZero expected 0 from it instead, and fails since.

Modification:

Remove testHeapBufferMemoryAddressIsZero.

Result:

The adaptive allocator's tests pass with netty#17820.
@lhotari

lhotari commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

@normanmaurer I have resolved the merge conflicts after #17820 was merged to 4.2.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@testlens-app

testlens-app Bot commented Oct 15, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

🚨 TestLens detected 2 failed tests 🚨

Failed Jobs without Test Failures

❌ Auto-port to 4.1 / Auto-porting to 4.1
❌ Auto-port to 5.0 / Auto-porting to 5.0

Test Summary

Tip

Inspect all details with the TestLens CLI: testlens pr 17767

Build PR / macos-aarch64-java11-boringssl build > Netty/Transport/Native/KQueue

Test Runs Flakiness
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendCompositeDirectByteBuf(TestInfo) ❌ 2% 🟡
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendWithoutBind(TestInfo) ❌ 3% 🟡

🏷️ Commit: bc01fbc
▶️ Tests: 134697 executed
⚪️ Checks: 33/33 completed

Test Failures

KQueueDatagramUnicastIPv6MappedTest > testSimpleSendCompositeDirectByteBuf(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-aarch64-java11-boringssl build)
org.opentest4j.AssertionFailedError
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend0(DatagramUnicastTest.java:368)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend(DatagramUnicastTest.java:194)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendCompositeDirectByteBuf(DatagramUnicastTest.java:128)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$3.run(DatagramUnicastTest.java:114)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$3.run(DatagramUnicastTest.java:111)
	at io.netty.testsuite.transport.AbstractComboTestsuiteTest.run(AbstractComboTestsuiteTest.java:52)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendCompositeDirectByteBuf(DatagramUnicastTest.java:111)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendWithoutBind(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-aarch64-java11-boringssl build)
org.opentest4j.AssertionFailedError
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend0(DatagramUnicastTest.java:368)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSend(DatagramUnicastTest.java:194)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendWithoutBind(DatagramUnicastTest.java:186)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$6.run(DatagramUnicastTest.java:180)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest$6.run(DatagramUnicastTest.java:177)
	at io.netty.testsuite.transport.AbstractComboTestsuiteTest.run(AbstractComboTestsuiteTest.java:52)
	at io.netty.testsuite.transport.socket.DatagramUnicastTest.testSimpleSendWithoutBind(DatagramUnicastTest.java:177)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)

Rerun Controls

Select tests to mute in this pull request:

  • KQueueDatagramUnicastIPv6MappedTest > testSimpleSendCompositeDirectByteBuf(TestInfo)
  • KQueueDatagramUnicastIPv6MappedTest > testSimpleSendWithoutBind(TestInfo)

Reuse successful test results:

  • ♻️ Only rerun the tests that failed or were muted before

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

chrisvest
chrisvest approved these changes Oct 15, 2026
View reviewed changes
@chrisvest chrisvest added needs-cherry-pick-4.1 This PR should be cherry-picked to 4.1 once merged. needs-cherry-pick-5.0 This PR should be cherry-picked to 5.0 once merged. labels Oct 15, 2026
@chrisvest
chrisvest merged commit b23c19d into netty:4.2 Oct 15, 2026
30 of 31 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@netty-project-bot

netty-project-bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Could not create auto-port PR.
Got conflicts when cherry-picking onto 4.1.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@netty-project-bot

netty-project-bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Could not create auto-port PR.
Got conflicts when cherry-picking onto 5.0.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@normanmaurer normanmaurer removed the needs-cherry-pick-4.1 This PR should be cherry-picked to 4.1 once merged. label Oct 16, 2026
@normanmaurer normanmaurer mentioned this pull request Oct 16, 2026
adapt mem5 #17851
Closed
normanmaurer pushed a commit that referenced this pull request Oct 16, 2026
@lhotari @normanmaurer
Make AdaptiveByteBuf.memoryAddress() faster (#17767)
0679ea3
Motivation:

An `AdaptiveByteBuf` is a segment of a chunk's root buffer.
`AdaptiveByteBuf._memoryAddress()` computes its address by calling the
root buffer's `_memoryAddress()` and adding the segment's offset. On
every call, the root buffer's `_memoryAddress()`:

1. checks `isAccessible()`,
2. calls `hasMemoryAddress()`,
3. calls `memoryAddress()`, which checks the reference count again in
`ensureAccessible()`.

These checks on the root buffer are redundant. The root buffer stays
accessible while the `AdaptiveByteBuf` holds a segment of its chunk, and
the root buffer's address doesn't change.

A gathering write in the native transports gets the memory address of
each buffer that it writes (`IovArray.add()`). In a profile of an Apache
Pulsar broker writing 8 KB messages, the checks on the root buffer were
3.3 % of the I/O threads' CPU.

Modification:

Existing behavior that this relies on:

- The address of an `AdaptiveByteBuf` is the root buffer's address plus
the segment's offset in the chunk (`startIndex`).
- The allocator calls `AdaptiveByteBuf.init()` when it hands out a
buffer. When a buffer grows beyond its segment, the reallocation moves
it to a new segment and calls `init()` again.

Changes:

- `Chunk` computes the root buffer's memory address once, when the chunk
is created.
- `AdaptiveByteBuf.init()` stores the buffer's memory address, the root
buffer's address plus `startIndex`, in a new field. When the root buffer
has no memory address, it stores 0, as
`AbstractByteBuf._memoryAddress()` returns for buffers without one.
- `AdaptiveByteBuf._memoryAddress()` returns the field, instead of
calling the root buffer's `_memoryAddress()`. The public
`memoryAddress()` still checks that the `AdaptiveByteBuf` itself is
accessible, and, since #17820, throws `UnsupportedOperationException`
when it has no memory address.
- `deallocate()` resets the field, so `_memoryAddress()` still returns 0
after the buffer is deallocated.
- A new test in `AdaptiveByteBufAllocatorTest`,
`testDirectBufferMemoryAddressFollowsItsSegment`, allocates two direct
buffers, so that the second one is likely at an offset above zero in the
chunk. It compares each buffer's `memoryAddress()` with the address of
the NIO buffer of the same range, which is computed from the chunk's
buffer separately. It compares again after a buffer grows into another
segment, and checks that `_memoryAddress()` returns 0 after release.
`AbstractByteBufTest.testMemoryAddressUnsupportedWhenNoMemoryAddress`
(#17820) covers the heap buffers.
- A new benchmark, `AdaptiveByteBufMemoryAddressBenchmark`, gets the
memory addresses of 16 direct buffers, as a gathering write does.

Result:

Each `memoryAddress()` call checks a reference count once, the
`AdaptiveByteBuf`'s own, instead of three times. The root buffer's
address is computed once per chunk; allocating and releasing a buffer
each add one field write.

`AdaptiveByteBufMemoryAddressBenchmark` with 16 buffers of 8 KB, on an
Intel i9-9980HK at a fixed 2.4 GHz, with Unsafe enabled
(`-Dio.netty.noUnsafe=false`), 2 alternating runs per side. Before is
4.2 at 60d9baf with only the benchmark added:

| | Before | After |
|---|---:|---:|
| JDK 21, run 1, ops/s | 18,497,697 ± 74,560 | 30,904,677 ± 69,876 |
| JDK 21, run 2, ops/s | 18,514,434 ± 31,468 | 30,915,307 ± 74,873 |
| JDK 25, run 1, ops/s | 18,532,696 ± 50,826 | 30,851,633 ± 296,462 |
| JDK 25, run 2, ops/s | 18,558,233 ± 23,243 | 30,877,691 ± 173,624 |

That's 3.38 ns per buffer before and 2.02 ns after on both JDKs: 67 %
more throughput, with warm caches and a monomorphic call site.

<details>
<summary>JMH output</summary>

```
Benchmark                                            (buffers)  (size)   Mode  Cnt         Score       Error  Units

JDK 21 before:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18497696.574 ± 74560.210  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18514434.341 ± 31467.599  ops/s

JDK 21 after:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30904677.380 ± 69875.648  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30915306.886 ± 74873.233  ops/s

JDK 25 before:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18532696.343 ± 50826.312  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18558232.849 ± 23243.203  ops/s

JDK 25 after:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30851632.966 ± 296461.862  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30877691.180 ± 173623.904  ops/s
```

</details>
@normanmaurer

normanmaurer commented Oct 16, 2026

Copy link
Copy Markdown
Member

Port for 5.0 #17852

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

normanmaurer added a commit that referenced this pull request Oct 16, 2026
@normanmaurer @lhotari
Port: Make AdaptiveByteBuf.memoryAddress() faster (#17767) (#17852)
7463c1a
Motivation:

An `AdaptiveByteBuf` is a segment of a chunk's root buffer.
`AdaptiveByteBuf._memoryAddress()` computes its address by calling the
root buffer's `_memoryAddress()` and adding the segment's offset. On
every call, the root buffer's `_memoryAddress()`:

1. checks `isAccessible()`,
2. calls `hasMemoryAddress()`,
3. calls `memoryAddress()`, which checks the reference count again in
`ensureAccessible()`.

These checks on the root buffer are redundant. The root buffer stays
accessible while the `AdaptiveByteBuf` holds a segment of its chunk, and
the root buffer's address doesn't change.

A gathering write in the native transports gets the memory address of
each buffer that it writes (`IovArray.add()`). In a profile of an Apache
Pulsar broker writing 8 KB messages, the checks on the root buffer were
3.3 % of the I/O threads' CPU.

Modification:

Existing behavior that this relies on:

- The address of an `AdaptiveByteBuf` is the root buffer's address plus
the segment's offset in the chunk (`startIndex`).
- The allocator calls `AdaptiveByteBuf.init()` when it hands out a
buffer. When a buffer grows beyond its segment, the reallocation moves
it to a new segment and calls `init()` again.

Changes:

- `Chunk` computes the root buffer's memory address once, when the chunk
is created.
- `AdaptiveByteBuf.init()` stores the buffer's memory address, the root
buffer's address plus `startIndex`, in a new field. When the root buffer
has no memory address, it stores 0, as
`AbstractByteBuf._memoryAddress()` returns for buffers without one.
- `AdaptiveByteBuf._memoryAddress()` returns the field, instead of
calling the root buffer's `_memoryAddress()`. The public
`memoryAddress()` still checks that the `AdaptiveByteBuf` itself is
accessible, and, since #17820, throws `UnsupportedOperationException`
when it has no memory address.
- `deallocate()` resets the field, so `_memoryAddress()` still returns 0
after the buffer is deallocated.
- A new test in `AdaptiveByteBufAllocatorTest`,
`testDirectBufferMemoryAddressFollowsItsSegment`, allocates two direct
buffers, so that the second one is likely at an offset above zero in the
chunk. It compares each buffer's `memoryAddress()` with the address of
the NIO buffer of the same range, which is computed from the chunk's
buffer separately. It compares again after a buffer grows into another
segment, and checks that `_memoryAddress()` returns 0 after release.
`AbstractByteBufTest.testMemoryAddressUnsupportedWhenNoMemoryAddress`
(#17820) covers the heap buffers.
- A new benchmark, `AdaptiveByteBufMemoryAddressBenchmark`, gets the
memory addresses of 16 direct buffers, as a gathering write does.

Result:

Each `memoryAddress()` call checks a reference count once, the
`AdaptiveByteBuf`'s own, instead of three times. The root buffer's
address is computed once per chunk; allocating and releasing a buffer
each add one field write.

`AdaptiveByteBufMemoryAddressBenchmark` with 16 buffers of 8 KB, on an
Intel i9-9980HK at a fixed 2.4 GHz, with Unsafe enabled
(`-Dio.netty.noUnsafe=false`), 2 alternating runs per side. Before is
4.2 at 60d9baf with only the benchmark added:

| | Before | After |
|---|---:|---:|
| JDK 21, run 1, ops/s | 18,497,697 ± 74,560 | 30,904,677 ± 69,876 |
| JDK 21, run 2, ops/s | 18,514,434 ± 31,468 | 30,915,307 ± 74,873 |
| JDK 25, run 1, ops/s | 18,532,696 ± 50,826 | 30,851,633 ± 296,462 |
| JDK 25, run 2, ops/s | 18,558,233 ± 23,243 | 30,877,691 ± 173,624 |

That's 3.38 ns per buffer before and 2.02 ns after on both JDKs: 67 %
more throughput, with warm caches and a monomorphic call site.

<details>
<summary>JMH output</summary>

```
Benchmark                                            (buffers)  (size)   Mode  Cnt         Score       Error  Units

JDK 21 before:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18497696.574 ± 74560.210  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18514434.341 ± 31467.599  ops/s

JDK 21 after:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30904677.380 ± 69875.648  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30915306.886 ± 74873.233  ops/s

JDK 25 before:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18532696.343 ± 50826.312  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  18558232.849 ± 23243.203  ops/s

JDK 25 after:
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30851632.966 ± 296461.862  ops/s
AdaptiveByteBufMemoryAddressBenchmark.memoryAddress         16    8192  thrpt   20  30877691.180 ± 173623.904  ops/s
```

</details>

Co-authored-by: Lari Hotari <[email protected]>
@normanmaurer normanmaurer removed the needs-cherry-pick-5.0 This PR should be cherry-picked to 5.0 once merged. label Oct 16, 2026
@lhotari lhotari mentioned this pull request Nov 2, 2026
[fix][sec] Upgrade Netty to 4.2.20 and netty-tcnative to 2.0.85 to address several CVEs and bugs apache/pulsar#27310
Merged
1 of 11 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@normanmaurer normanmaurer normanmaurer approved these changes
@chrisvest chrisvest chrisvest approved these changes
@franz1981 franz1981 franz1981 approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

4.2.20.Final

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

5 participants

@lhotari @franz1981 @normanmaurer @netty-project-bot @chrisvest
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.