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 — AdaptivePoolingAllocator EventLoop Magazine's affinity by franz1981 · Pull Request #14047 · netty/netty

AdaptivePoolingAllocator EventLoop Magazine's affinity #14047

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
chrisvest merged 3 commits into netty:main from franz1981:main_event_executor_magazines
May 14, 2024

Uh oh!

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

Merged

AdaptivePoolingAllocator EventLoop Magazine's affinity #14047

Changes from 1 commit
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
344bf9b
AdaptivePoolingAllocator EventLoop Magazine's affinity
franz1981 May 10, 2024
82418f4
Fix by chris comment
franz1981 May 13, 2024
304c5ce
Add Magazine::close on thread local's remove
franz1981 May 14, 2024
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

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

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

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

Diff view
Diff view
Next Next commit
AdaptivePoolingAllocator EventLoop Magazine's affinity
Motivation:

AdaptivePoolingAllocator uses some shared Magazines hoping thread's id
distribution to improve contended behaviour, but event loops threads can
just uses their own Magazine(s) and save 2 atomic operations (write
lock/unlock) in the hot path, further improving performance.

Modification:

Implements dedicated event loop Magazines

Result:

Better allocation performance for event loop threads
  • Loading branch information

Uh oh!

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

@franz1981
franz1981 committed May 10, 2024
commit 344bf9bc9c1e10faa123f27b31f2b0ebacb2a637

There are no files selected for viewing

91 changes: 82 additions & 9 deletions 91 buffer/src/main/java/io/netty5/buffer/adapt/AdaptivePoolingAllocator.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,20 @@
import io.netty5.buffer.internal.CleanerDrop;
import io.netty5.buffer.internal.InternalBufferUtils;
import io.netty5.util.NettyRuntime;
import io.netty5.util.concurrent.EventExecutor;
import io.netty5.util.concurrent.FastThreadLocal;
import io.netty5.util.concurrent.FastThreadLocalThread;
import io.netty5.util.internal.PlatformDependent;
import io.netty5.util.internal.SystemPropertyUtil;
import io.netty5.util.internal.ThreadExecutorMap;
import org.jetbrains.annotations.NotNull;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Arrays;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.StampedLock;
import java.util.function.Supplier;

Expand Down Expand Up @@ -69,6 +75,9 @@
* The {@link #createSharedChunkQueue()} method can be overridden to customize this queue.
*/
public class AdaptivePoolingAllocator implements BufferAllocator {

private static final int EXPANSION_ATTEMPTS = 3;
private static final int INITIAL_MAGAZINES = 4;
private static final int RETIRE_CAPACITY = 4 * 1024;
private static final int MIN_CHUNK_SIZE = 128 * 1024;
private static final int MAX_STRIPES = NettyRuntime.availableProcessors() * 2;
Expand All @@ -93,29 +102,59 @@ public class AdaptivePoolingAllocator implements BufferAllocator {
protected static final int CENTRAL_QUEUE_CAPACITY = SystemPropertyUtil.getInt(
"io.netty5.allocator.centralQueueCapacity", NettyRuntime.availableProcessors());

private static final Object NO_MAGAZINE = Boolean.TRUE;

private final AllocationType allocationType;
private final MemoryManager manager;
private final Queue<Buffer> centralQueue;
private final AllocatorControl allocatorControl;
private final StampedLock magazineExpandLock;
private volatile Magazine[] magazines;
private volatile boolean closed;
private final FastThreadLocal<Object> threadLocalMagazine;
private final Set<Magazine> liveCachedMagazines;

public AdaptivePoolingAllocator() {
this(PlatformDependent.directBufferPreferred());
}

public AdaptivePoolingAllocator(boolean direct) {
this(MemoryManager.instance(), direct);
this(MemoryManager.instance(), direct, true);
}

public AdaptivePoolingAllocator(MemoryManager manager, boolean direct) {
AdaptivePoolingAllocator(MemoryManager manager, boolean direct, boolean eventExecutorMagazines) {
allocationType = direct ? StandardAllocationTypes.OFF_HEAP : StandardAllocationTypes.ON_HEAP;
this.manager = manager;
centralQueue = requireNonNull(createSharedChunkQueue());
allocatorControl = new SimpleAllocatorControl(this);
magazineExpandLock = new StampedLock();
Magazine[] mags = new Magazine[4];
if (eventExecutorMagazines) {
final Set<Magazine> liveMagazines = new CopyOnWriteArraySet<>();
threadLocalMagazine = new FastThreadLocal<>() {
@Override
protected Object initialValue() {
EventExecutor executor = ThreadExecutorMap.currentExecutor();
if (executor == null) {
return NO_MAGAZINE;
}
Magazine mag = new Magazine(AdaptivePoolingAllocator.this, executor);
liveMagazines.add(mag);
return mag;
}

@Override
protected void onRemoval(final Object value) {
if (value != NO_MAGAZINE) {
liveMagazines.remove(value);
}
}
};
liveCachedMagazines = liveMagazines;
} else {
threadLocalMagazine = null;
liveCachedMagazines = null;
}
Magazine[] mags = new Magazine[INITIAL_MAGAZINES];
for (int i = 0; i < mags.length; i++) {
mags[i] = new Magazine(this);
}
Expand Down Expand Up @@ -165,7 +204,17 @@ public Buffer allocate(int size) {
InternalBufferUtils.assertValidBufferSize(size);
if (size <= MAX_CHUNK_SIZE) {
int sizeBucket = AllocationStatistics.sizeBucket(size); // Compute outside of Magazine lock for better ILP.
long threadId = threadId(Thread.currentThread());
FastThreadLocal<Object> threadLocalMagazine = this.threadLocalMagazine;
Thread currentThread = Thread.currentThread();
if (threadLocalMagazine != null && currentThread instanceof FastThreadLocalThread) {
// this is going to exclude virtual threads,
// but sadly even custom event executor which are not FastThreadLocalThreads
Comment thread
franz1981 marked this conversation as resolved.
Resolved

Uh oh!

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

Object mag = threadLocalMagazine.get();
if (mag != NO_MAGAZINE) {
return ((Magazine) mag).allocate(size, sizeBucket);
}
}
long threadId = threadId(currentThread);
int expansions = 0;
Magazine[] mags;
do {
Expand All @@ -184,7 +233,7 @@ public Buffer allocate(int size) {
}
}
expansions++;
} while (expansions <= 3 && tryExpandMagazines(mags.length));
} while (expansions <= EXPANSION_ATTEMPTS && tryExpandMagazines(mags.length));
}
// The magazines failed us, or the buffer is too big to be pooled. Allocate unpooled buffer.
return manager.allocateShared(allocatorControl, size, standardDrop(manager), allocationType);
Expand Down Expand Up @@ -241,6 +290,22 @@ public void close() {
} finally {
magazineExpandLock.unlockWrite(magsExpandWriteLock);
}
if (liveCachedMagazines != null) {
liveCachedMagazines.forEach(mag -> {
try {
mag.ownerEventExecutor.execute(() -> {
threadLocalMagazine.remove();
// this is to prevent that a subsequent request will try to create a new Magazine
threadLocalMagazine.set(NO_MAGAZINE);
Comment thread
franz1981 marked this conversation as resolved.
Resolved

Uh oh!

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

drainCloseCentralQueue();
});
} catch (Throwable ignore) {
// if we've been rejected here, it's likely the event executor will take care of remove it
// but if the event executor was running on an FastThreadLocalThread which doesn't remove it,
// we're in trouble :"(
}
});
}
drainCloseCentralQueue();
}

Expand Down Expand Up @@ -273,6 +338,7 @@ private static class AllocationStatistics extends StampedLock {
private static final int HISTO_MAX_BUCKET_MASK = HISTO_BUCKET_COUNT - 1;

protected final AdaptivePoolingAllocator parent;
protected final EventExecutor ownerEventExecutor;
private final short[][] histos = {
new short[HISTO_BUCKET_COUNT], new short[HISTO_BUCKET_COUNT],
new short[HISTO_BUCKET_COUNT], new short[HISTO_BUCKET_COUNT],
Expand All @@ -286,8 +352,9 @@ private static class AllocationStatistics extends StampedLock {
private volatile int sharedPrefChunkSize = MIN_CHUNK_SIZE;
protected volatile int localPrefChunkSize = MIN_CHUNK_SIZE;

private AllocationStatistics(AdaptivePoolingAllocator parent) {
private AllocationStatistics(AdaptivePoolingAllocator parent, EventExecutor ownerEventExecutor) {
this.parent = parent;
this.ownerEventExecutor = ownerEventExecutor;
}

protected void recordAllocationSize(int bucket) {
Expand Down Expand Up @@ -326,8 +393,10 @@ private void rotateHistograms() {
int percentileSize = 1 << sizeBucket + HISTO_MIN_BUCKET_SHIFT;
int prefChunkSize = Math.max(percentileSize * BUFS_PER_CHUNK, MIN_CHUNK_SIZE);
localPrefChunkSize = prefChunkSize;
for (Magazine mag : parent.magazines) {
prefChunkSize = Math.max(prefChunkSize, mag.localPrefChunkSize);
if (ownerEventExecutor != null) {
Comment thread
franz1981 marked this conversation as resolved.
Resolved

Uh oh!

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

for (Magazine mag : parent.magazines) {
prefChunkSize = Math.max(prefChunkSize, mag.localPrefChunkSize);
}
}
if (sharedPrefChunkSize != prefChunkSize) {
// Preferred chunk size changed. Increase check frequency.
Expand Down Expand Up @@ -373,7 +442,11 @@ private static final class Magazine extends AllocationStatistics {
private volatile Buffer nextInLine;

Magazine(AdaptivePoolingAllocator parent) {
super(parent);
super(parent, null);
}

Magazine(AdaptivePoolingAllocator parent, EventExecutor ownerEventExecutor) {
super(parent, ownerEventExecutor);
}

public Buffer allocate(int size, int sizeBucket) {
Expand Down
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 01402809 — 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.