Repository: netty/netty
File: buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java (Java)

Code before:
                long writeLock = mag.tryWriteLock();
                if (writeLock != 0) {
                    try {
                        return mag.allocate(size, sizeBucket, maxCapacity, buf);
                    } finally {
                        mag.unlockWrite(writeLock);
                    }
                }
            }
            expansions++;
        } while (expansions <= 3 && tryExpandMagazines(mags.length));
        return null;
    }

    /**
     * Allocate into the given buffer. Used by {@link AdaptiveByteBuf#capacity(int)}.
     */
    void allocate(int size, int maxCapacity, AdaptiveByteBuf into) {
        Magazine magazine = into.chunk.magazine;
        AdaptiveByteBuf result = allocate(size, maxCapacity, Thread.currentThread(), into);
        if (result == null) {
            // Create a one-off chunk for this allocation.
            AbstractByteBuf innerChunk = (AbstractByteBuf) chunkAllocator.allocate(size, maxCapacity);
            ChunkByteBuf chunk = new ChunkByteBuf(innerChunk, magazine, false);
            chunk.readInitInto(into, size, maxCapacity);
        }
    }

    long usedMemory() {
        long sum = 0;
        for (ByteBuf byteBuf : centralQueue) {
            sum += byteBuf.capacity();
        }
        for (Magazine magazine : magazines) {
            sum += magazine.usedMemory.get();
        }
        return sum;
    }

    private boolean tryExpandMagazines(int currentLength) {
        if (currentLength >= MAX_STRIPES) {
            return true;
        }
        long writeLock = magazineExpandLock.tryWriteLock();
        if (writeLock != 0) {
            try {
                Magazine[] mags = magazines;
                if (mags.length >= MAX_STRIPES || mags.length > currentLength) {
                    return true;
                }
                Magazine[] expanded = Arrays.copyOf(mags, mags.length * 2);

Review comment (performance):
I'm not very convinced about having `ThreadExecutorMap.currentExecutor()` in the hot path, really...

@chrisvest any other ideas?

Code after:
     * <p>
     * Each Magazine can only hold two chunks at any one time: the chunk it currently allocates from,
     * and the next-in-line chunk which will be used for allocation once the current one has been used up.
     * This queue will be used by magazines to share any excess chunks they allocate, so that they don't need to
     * allocate new chunks when their current and next-in-line chunks have both been used up.
     * <p>
     * The simplest implementation of this method is to return a new {@link ConcurrentLinkedQueue}.
     * However, the {@code CLQ} is unbounded, and this means there's no limit to how many chunks can be cached in this
     * queue.
     * <p>
     * Each chunk in this queue can be up to {@link #MAX_CHUNK_SIZE} in size, so it is recommended to use a bounded
     * queue to limit the maximum memory usage.
     * <p>
     * The default implementation will create a bounded queue with a capacity of {@link #CENTRAL_QUEUE_CAPACITY}.
     *
     * @return A new multi-producer, multi-consumer queue.
     */
    private static Queue<ChunkByteBuf> createSharedChunkQueue() {
        return PlatformDependent.newFixedMpmcQueue(CENTRAL_QUEUE_CAPACITY);
    }

    ByteBuf allocate(int size, int maxCapacity) {
        if (size <= MAX_CHUNK_SIZE) {
            Thread currentThread = Thread.currentThread();
            boolean willCleanupFastThreadLocals = FastThreadLocalThread.willCleanupFastThreadLocals(currentThread);
            AdaptiveByteBuf buf = AdaptiveByteBuf.newInstance(willCleanupFastThreadLocals);
            AdaptiveByteBuf result = allocate(size, maxCapacity, currentThread, buf);
            if (result != null) {
                return result;
            }
            // Return the buffer we pulled from the recycler but didn't use.
            buf.release();
        }
        // The magazines failed us, or the buffer is too big to be pooled.
        return chunkAllocator.allocate(size, maxCapacity);
    }

    private AdaptiveByteBuf allocate(int size, int maxCapacity, Thread currentThread, AdaptiveByteBuf buf) {
        int sizeBucket = AllocationStatistics.sizeBucket(size); // Compute outside of Magazine lock for better ILP.
        FastThreadLocal<Object> threadLocalMagazine = this.threadLocalMagazine;
        if (threadLocalMagazine != null && currentThread instanceof FastThreadLocalThread) {
            Object mag = threadLocalMagazine.get();
            if (mag != NO_MAGAZINE) {
                return ((Magazine) mag).allocate(size, sizeBucket, maxCapacity, buf);
            }
        }
        long threadId = currentThread.getId();
        Magazine[] mags;
        int expansions = 0;
        do {
            mags = magazines;