GeezerVison is showing github.com — Reduce thread context check overhead by ninja- · Pull Request #4412 · netty/netty
Conversation
ThreadLocal is a very significant overhead in critical areas of the code.
So big it easilly gets to "first hot method by self-time" while benchmarking netty internals relating to the I/O flow
Usage of ThreadLocal will never be free no matter the implementation, because of the
Thread.currentThread() call.
Modifications:
Reduce thread context checks when possible by storing recycler's stack handle in places
when the caller is either a thread-local subclass or .get() and .recycle() are only allowed to be called only inside the event loop.
Result:
Less overhead. Improvement visible in profiler and benchmarks.
❗ Not related to #4402 ❗
PART 1 :
- PoolArena,PooledByteBufAllocator,PoolThreadCache,Pooled[Unsafe]DirectByteBuf
- minor: remove casts in recycler's legacy recycle() method
- cache thread-local stacks for mentioned classes for both get() and recycle() whenever possible
(not always possible to skip thread check for recycle() when we have user code. it's optimized in places when we are sure of the thread i.e. always inside the event loop 👍 )
- modify Recycler to suit the need
- deduplicate the stack handles by assigning them to Stack
- maybe cleanup and get rid of per-item close in PoolThreadCache (make it an argument call)
Critical Bugs:
- store Pooled*Buf local recycler stacks in the proper place (notes in post below)
- fix MemoryRegionCache.newEntry while not doing a thread-local query somehow... (notes in post below)
- mark outbound buffer entries as unsafe when changing event loops
PART 2:
- Add ChannelHandlerContext.locAlloc() and use it in most handlers
- removes yet another ThreadLocal query by replacing with cache
- stored on EventLoop's object
- allowed only when inside the correct EventLoop
- move to singlethreadexecutor instead of epolleventloop
PART 3:
- replace IovArrayThreadLocal with IovArray on EpollEventLoop's object to remove unneeded ThreadLocal queries for every write
PART 4:
- [make FastThreadLocal wrap around Java's ThreadLocal to keep the performance on par
- move the InternalThreadLocalMap's backend to Java's ThreadLocal
the map is still used here and there
PART 4:
-
[x] AbstractByteBuf.threadLocal() - adds a flag so it's going to use recycleSameThread(). Call the flag on important handlers like BTBDecoder and MTMEncoder
or maybee ByteBufAllocator#ioBuffer/directBuffer(true) as a nicer api
(introduce an interface called LocalByteBufAllocator and hook with locAlloc() )
- fix checkstyle
These 4 commits will say goodbye to ThreadLocals occupying hot methods 😃
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@Scottmitch I'll get the CLA soon. I see two other places to get the ThreadLocals out. For example ctx.alloc() (which is used like over and over to rotate the i/o buffers) could skip PooledAllocator's threadCache.get() and use one that's per-eventloop. It wouldn't be fully safe with user code so something like localAlloc() and use that whenever possible in handlers(in event loop only)
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@ninja- maybe not spent too much time on this before we validated it ? Not want to waste your time if at the end there are issues with the approach. I hope to have time to review tomorrow.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@normanmaurer it's 100% thread-safe as in won't race etc.. But yeah you should review when you can
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@ninja- btw if you submit PR's please ensure that these build without errors. This PER has check-style errors.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@normanmaurer yeah as usual...are there any tools to do this at least?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
mvn clean package should fail if there is a checkstyle error
Am 29.10.2015 um 20:23 schrieb ninja [email protected]:
@normanmaurer yeah as usual...are there any tools to do this at least?
—
Reply to this email directly or view it on GitHub.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
no I mean like get the formatting fixed with tool. Intellij will break it by itself as you can see with the loops
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Ok I'll fix the checkstyle.
I have just finished the second part which creates ctx.locAlloc() and uses that in most handlers; this should drop even more ThreadLocal overhead. That will be in a seperate commit.
As the last feature I am moving IovArrayThreadLocal to be stored in EpollEventLoop.
These 3 commits will say goodbye to ThreadLocals occupying hot methods 😃 🎉
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
#4417
I was looking forward to doing some deep digging, but got disappointed :(.
No worries @buchgr @normanmaurer, it still causes noticeable overhead
that I am going to cover (✌ ゚ ∀ ゚)☞
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
I don't think the http test could be related to the changes. This http test will fail 10% of the time on my pc.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Found some issues to fix already, additional reviews welcome.
Notes:
- stressTest() could throw "already recycled" from the
PoolThreadCache.MemoryRegionCache.Entry.recycleUnsafe() while coming from free() when thread dies. Happened only once, hard to repro.
What's even more weird is that call to recyclerHandle.recycle() took the route of "stack.thread == Thread.currentThread()" which is unusual since free() is supposed to be called from another thread than the allocator thread... its not death watcher but coming from thread local
- stressTest() would hang and timeout in about 10-15% of tries
18:18:39.148 [main] DEBUG i.n.u.i.l.InternalLoggerFactory - Using SLF4J as the default logging framework
18:18:39.167 [main] DEBUG i.n.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
18:18:39.168 [main] DEBUG i.n.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
18:18:39.169 [main] DEBUG i.n.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
18:18:39.174 [main] DEBUG i.n.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: true
18:18:39.189 [main] DEBUG i.n.util.internal.PlatformDependent - Java version: 8
18:18:39.189 [main] DEBUG i.n.util.internal.PlatformDependent - -Dio.netty.noUnsafe: false
18:18:39.189 [main] DEBUG i.n.util.internal.PlatformDependent - sun.misc.Unsafe: available
18:18:39.190 [main] DEBUG i.n.util.internal.PlatformDependent - -Dio.netty.noJavassist: false
18:18:39.318 [main] DEBUG i.n.util.internal.PlatformDependent - Javassist: available
18:18:39.318 [main] DEBUG i.n.util.internal.PlatformDependent - -Dio.netty.tmpdir: /tmp (java.io.tmpdir)
18:18:39.318 [main] DEBUG i.n.util.internal.PlatformDependent - -Dio.netty.bitMode: 64 (sun.arch.data.model)
18:18:39.318 [main] DEBUG i.n.util.internal.PlatformDependent - -Dio.netty.noPreferDirect: false
18:18:39.328 [main] DEBUG io.netty.buffer.AbstractByteBuf - -Dio.netty.buffer.bytebuf.checkAccessible: true
18:18:39.330 [main] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
18:18:39.331 [main] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.maxRecords: 4
18:18:39.370 [main] DEBUG i.n.c.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 16
18:18:39.411 [main] DEBUG io.netty.channel.DefaultChannelId - -Dio.netty.processId: 8685 (auto-detected)
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numHeapArenas: 16
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.numDirectArenas: 16
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.pageSize: 8192
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxOrder: 11
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.chunkSize: 16777216
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.tinyCacheSize: 512
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.smallCacheSize: 256
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.normalCacheSize: 64
18:18:39.442 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.maxCachedBufferCapacity: 32768
18:18:39.443 [main] DEBUG i.n.buffer.PooledByteBufAllocator - -Dio.netty.allocator.cacheTrimInterval: 8192
18:18:39.453 [main] DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.allocator.type: pooled
18:18:39.453 [main] DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.threadLocalDirectBufferSize: 65536
18:18:39.453 [main] DEBUG io.netty.buffer.ByteBufUtil - -Dio.netty.maxThreadLocalCharBufferSize: 16384
18:18:39.518 [main] DEBUG i.n.u.i.JavassistTypeParameterMatcherGenerator - Generated: io.netty.util.internal.__matchers__.java.net.InetSocketAddressMatcher
18:18:39.548 [defaultEventLoopGroup-3-1] DEBUG io.netty.util.Recycler - -Dio.netty.recycler.maxCapacity.maxCapacity: 262144
18:18:40.549 [defaultEventLoopGroup-2-2] DEBUG io.netty.buffer.PoolThreadCache - Freed 513 thread-local buffer(s) from thread: defaultEventLoopGroup-2-2
Exception in thread "defaultEventLoopGroup-3-1" java.lang.IllegalStateException: recycled already
at io.netty.util.Recycler$Stack.push(Recycler.java:425)
at io.netty.util.Recycler$DefaultHandle.recycle(Recycler.java:162)
at io.netty.buffer.PoolThreadCache$MemoryRegionCache$Entry.recycleUnsafe(PoolThreadCache.java:483)
at io.netty.buffer.PoolThreadCache$MemoryRegionCache.freeEntry(PoolThreadCache.java:459)
at io.netty.buffer.PoolThreadCache$MemoryRegionCache.free(PoolThreadCache.java:431)
at io.netty.buffer.PoolThreadCache$MemoryRegionCache.free(PoolThreadCache.java:423)
at io.netty.buffer.PoolThreadCache.free(PoolThreadCache.java:266)
at io.netty.buffer.PoolThreadCache.free(PoolThreadCache.java:257)
at io.netty.buffer.PoolThreadCache.free0(PoolThreadCache.java:238)
at io.netty.buffer.PoolThreadCache.free(PoolThreadCache.java:234)
at io.netty.buffer.PooledByteBufAllocator$PoolThreadLocalCache.onRemoval(PooledByteBufAllocator.java:361)
at io.netty.buffer.PooledByteBufAllocator$PoolThreadLocalCache.onRemoval(PooledByteBufAllocator.java:332)
at io.netty.util.concurrent.FastThreadLocal.remove(FastThreadLocal.java:226)
at io.netty.util.concurrent.FastThreadLocal.removeAll(FastThreadLocal.java:67)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:139)
at java.lang.Thread.run(Thread.java:745)
Disconnected from the target VM, address: '127.0.0.1:38088', transport: 'socket'
One logic mistake I see is that DirectArena is in some cases shared/reused accross threads so that's something to fix for sure but fixing it doesn't solve the mentioned problem of timeout/recycled already.
The problem is that the passed stack handle is owned by other thread so I am checking where is my mistake like assuming some parts aren't shared.
@Override
@SuppressWarnings("all")
public T get() {
if (thread != Thread.currentThread()) {
throw new UnsupportedOperationException("you dont own this stack");
}
DefaultHandle handle = pop();
if (handle == null) {
handle = newHandle();
handle.value = parent.newObject(handle);
}
return (T) handle.value;
}
This temporary guard is successful in triggering the problem.
OK now I know exactly what is wrong in my impl currently:
- these stack handles for PooledDirectByteBuf can't be here and may need to be passed around as PoolArena is sometimes shared (for now the stack query will be left as-is).
Solution: store buf stacks on PoolThreadCache instead of PoolArena.Direct and pass the cache instance down to PoolArena.Direct.newByteBuf(...)
- PoolArena.free -> PoolThreadCache.add caused the mentioned problem (PoolArena being shared). I am not sure what's the best way to get around this, but I'll think of something.
The main problem here is that the buffer may not be deallocated on the same thread as it was allocated on, and it's trying to get the memory region back to the it's original-thread cache.
It's not a problem by itself, the problematic part is: how to create a new MemoryRegionCache$Entry in such case without doing thread-local lookup...
Solution ideas(pick one):
- Create a mini-recycler for MemoryRegionCache$Entry based on SPMC queue.
- Defer the need to use recycler in MRC Entry.add(..) by having one object representing chunk & handle, and then directly add that object to the used "queue". I don't want to do this because memory usage.
- Make "handle" global by some mapping so just the long would be enough
- ????
ideas @normanmaurer ? anything that wouldn't involve Thread.currentThread() and wouldn't break if the buffer were to be deallocated from another thread than allocated.
It's really just about creating the Entries(without allocation spam) as the "queue" is fine otherwise.
I think the solution is to use PoolSubpage 😄 I thought that the per-buffer subpage didn't have a representation in full object.
EDIT: seems like PoolSubpage isn't exclusively per-buffer but I have an idea on what to do with it.
I am going to store just the PoolSubpages in the queue and have the PoolSubpages contain an array of valid handles.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.
ignore, I did an empty commit to force the bot to re-run the tests
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@ninja- so just to ensure I get the idea... Basically you want to remove the "ThreadLocal" lookup when you know that for example everything is always done from within the EventLoop of a Channel. Like for example in ChannelOutboundBuffer. Is this correct ?
I did not have the time yet to have a deep look but one thing that I don't like from a quick look is that you "pulled" the ByteBufAllocator into the EventLoop. An EventLoop should not be aware an ByteBufAllocator. This blur the separation of different parts of the API and different responsibilities.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
I did not have the time yet to have a deep look but one thing that I don't like from a quick look is that you "pulled" the ByteBufAllocator into the EventLoop. An EventLoop should not be aware an ByteBufAllocator. This blur the separation of different parts of the API and different responsibilities.
Hmm I did this to reduce memory usage. Like, the local allocator instance needs to be created "per something". I didn't want to make an instance per ChannelPipeline etc. so if you have an idea on how to hide it from EventLoop then I could get it out of EventLoop in patch 2
Basically, EventLoop is always with us when we need an allocator when operating on channels and it's per-thread. It's an alternative to looking up data on Thread object.
so just to ensure I get the idea... Basically you want to remove the "ThreadLocal" lookup when you know that for example everything is always done from within the EventLoop of a Channel. Like for example in ChannelOutboundBuffer. Is this correct ?
That's correct.
a) when we are sure that get() and recycle() are happening only within local event loop, I use the optimized version
b) a second case is when we know that the instance of caller class is a thread-local by itself like the PoolThreadCache I also do the same thing when possible
c) the optimized recycler calls aren't used in places when user code break the threading, like when the deallocate() could be called outside of the thread-loop, by the user. I am really careful about this.
(me) EDIT: seems like PoolSubpage isn't exclusively per-buffer but I have an idea on what to do with it.
I am going to store just the PoolSubpages in the queue and have the PoolSubpages contain an array of valid handles. Then queue.poll() for a PoolSubpage with at least one cached handle when allocating.
Give me a tip: what's the maximum number of valid handles for a PoolSubpage so I can hardcode array length there? Or maybe you could think about better ways to cache valid PoolSubpage parts? (it's basically the ID coming from PoolSubpage#allocate()
Hmm I think I see the relevant function in PoolSubpage to do such thing.
The way memory regions are cached(for speed) needs to be rethinked here to avoid need for Recycler (again, just these damn Entry objects! need another good way to cache PoolSubpage+handle combo) and work with possibility multiple threads caching region of same PoolSubpage at once(so working directly on PoolSubpage fields wouldn't work).
It's worth reminding that the reason for this cache is primarily to skip the synchronized block that happens when allocating. So anything that would cache regions at PoolSubpage fields wouldn't work as would also need this synnc.
After thinking about this for a few hours I'd seriously do an off-heap data structure for this combo and only leave the thread local query if !hasUnsafe(). But then I am left with a memory address to put into queue and it will be boxed every time 😢
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@Scottmitch @normanmaurer fyi finished my list.
I noticed when testing that it doesn't recycle outbound entries and spams them, will investigate. Otherwise it's tested and imo thread-safe.
(EDIT: this was caused by improper "message squasher" merge, so not related to this PR. nevermind)
One last thing to fix (related to the stressTest) aaand it's done
EDIT: it's doooone. Wiped every single ThreadLocal out of the profiler results @normanmaurer \o/
(app code required buf.local(true) here and there)
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@ninja- - Can you report benchmark results which demonstrate the improvements claimed by this PR?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@Scottmitch you know this kind of improvement that benchmark doesn't show but profiler does? That's one of them...
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@ninja- sorry if this sounds harsh but without a proof I can not accept this. This PR touches so many places that I'm not feeling "convinced" enough without seeing it myself. Maybe it would be easier if you just do "small / isolated" changes, proof it and open a PR.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
hello @normanmaurer any chance you could revisit this PR?
(it's been working correctly for me ever since - I am still using it)
I remember you tried to pull the 3rd patch once and quickly reverted when figuring out it's not thread safe in ForkJoinPool. Well I really can't agree on that. Could you explain that?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
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.
|