package io.netty.util;

import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.internal.MathUtil;
import io.netty.util.internal.ObjectCleaner;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/* JADX INFO: loaded from: classes.dex */
public abstract class Recycler<T> {
    private static final int DEFAULT_INITIAL_MAX_CAPACITY_PER_THREAD = 4096;
    private static final int DEFAULT_MAX_CAPACITY_PER_THREAD;
    private static final FastThreadLocal<Map<Stack<?>, WeakOrderQueue>> DELAYED_RECYCLED;
    private static final AtomicInteger ID_GENERATOR;
    private static final int INITIAL_CAPACITY;
    private static final int LINK_CAPACITY;
    private static final int MAX_DELAYED_QUEUES_PER_THREAD;
    private static final int MAX_SHARED_CAPACITY_FACTOR;
    private static final Handle NOOP_HANDLE;
    private static final int OWN_THREAD_ID;
    private static final int RATIO;
    private static final InternalLogger logger;
    private final int maxCapacityPerThread;
    private final int maxDelayedQueuesPerThread;
    private final int maxSharedCapacityFactor;
    private final int ratioMask;
    private final FastThreadLocal<Stack<T>> threadLocal;

    public static final class DefaultHandle<T> implements Handle<T> {
        public boolean hasBeenRecycled;
        private int lastRecycledId;
        private int recycleId;
        private Stack<?> stack;
        private Object value;

        public DefaultHandle(Stack<?> stack) {
            this.stack = stack;
        }

        @Override // io.netty.util.Recycler.Handle
        public void recycle(Object obj) {
            if (obj != this.value) {
                throw new IllegalArgumentException("object does not belong to handle");
            }
            this.stack.push(this);
        }
    }

    public interface Handle<T> {
        void recycle(T t2);
    }

    public static final class Stack<T> {
        public final AtomicInteger availableSharedCapacity;
        private WeakOrderQueue cursor;
        private DefaultHandle<?>[] elements;
        private int handleRecycleCount = -1;
        private volatile WeakOrderQueue head;
        private final int maxCapacity;
        public final int maxDelayedQueues;
        public final Recycler<T> parent;
        private WeakOrderQueue prev;
        private final int ratioMask;
        private int size;
        public final WeakReference<Thread> threadRef;

        public Stack(Recycler<T> recycler, Thread thread, int i2, int i3, int i4, int i5) {
            this.parent = recycler;
            this.threadRef = new WeakReference<>(thread);
            this.maxCapacity = i2;
            this.availableSharedCapacity = new AtomicInteger(Math.max(i2 / i3, Recycler.LINK_CAPACITY));
            this.elements = new DefaultHandle[Math.min(Recycler.INITIAL_CAPACITY, i2)];
            this.ratioMask = i4;
            this.maxDelayedQueues = i5;
        }

        private void pushLater(DefaultHandle<?> defaultHandle, Thread thread) {
            Map map = (Map) Recycler.DELAYED_RECYCLED.get();
            WeakOrderQueue weakOrderQueueAllocate = (WeakOrderQueue) map.get(this);
            if (weakOrderQueueAllocate == null) {
                if (map.size() >= this.maxDelayedQueues) {
                    map.put(this, WeakOrderQueue.DUMMY);
                    return;
                }
                weakOrderQueueAllocate = WeakOrderQueue.allocate(this, thread);
                if (weakOrderQueueAllocate == null) {
                    return;
                } else {
                    map.put(this, weakOrderQueueAllocate);
                }
            } else if (weakOrderQueueAllocate == WeakOrderQueue.DUMMY) {
                return;
            }
            weakOrderQueueAllocate.add(defaultHandle);
        }

        private void pushNow(DefaultHandle<?> defaultHandle) {
            if ((((DefaultHandle) defaultHandle).recycleId | ((DefaultHandle) defaultHandle).lastRecycledId) != 0) {
                throw new IllegalStateException("recycled already");
            }
            ((DefaultHandle) defaultHandle).recycleId = ((DefaultHandle) defaultHandle).lastRecycledId = Recycler.OWN_THREAD_ID;
            int i2 = this.size;
            if (i2 >= this.maxCapacity || dropHandle(defaultHandle)) {
                return;
            }
            DefaultHandle<?>[] defaultHandleArr = this.elements;
            if (i2 == defaultHandleArr.length) {
                this.elements = (DefaultHandle[]) Arrays.copyOf(defaultHandleArr, Math.min(i2 << 1, this.maxCapacity));
            }
            this.elements[i2] = defaultHandle;
            this.size = i2 + 1;
        }

        public boolean dropHandle(DefaultHandle<?> defaultHandle) {
            if (defaultHandle.hasBeenRecycled) {
                return false;
            }
            int i2 = this.handleRecycleCount + 1;
            this.handleRecycleCount = i2;
            if ((i2 & this.ratioMask) != 0) {
                return true;
            }
            defaultHandle.hasBeenRecycled = true;
            return false;
        }

        public int increaseCapacity(int i2) {
            int length = this.elements.length;
            int i3 = this.maxCapacity;
            do {
                length <<= 1;
                if (length >= i2) {
                    break;
                }
            } while (length < i3);
            int iMin = Math.min(length, i3);
            DefaultHandle<?>[] defaultHandleArr = this.elements;
            if (iMin != defaultHandleArr.length) {
                this.elements = (DefaultHandle[]) Arrays.copyOf(defaultHandleArr, iMin);
            }
            return iMin;
        }

        public DefaultHandle<T> newHandle() {
            return new DefaultHandle<>(this);
        }

        public DefaultHandle<T> pop() {
            int i2 = this.size;
            if (i2 == 0) {
                if (!scavenge()) {
                    return null;
                }
                i2 = this.size;
            }
            int i3 = i2 - 1;
            Object[] objArr = this.elements;
            DefaultHandle<T> defaultHandle = (DefaultHandle<T>) objArr[i3];
            objArr[i3] = null;
            if (((DefaultHandle) defaultHandle).lastRecycledId != ((DefaultHandle) defaultHandle).recycleId) {
                throw new IllegalStateException("recycled multiple times");
            }
            ((DefaultHandle) defaultHandle).recycleId = 0;
            ((DefaultHandle) defaultHandle).lastRecycledId = 0;
            this.size = i3;
            return defaultHandle;
        }

        public void push(DefaultHandle<?> defaultHandle) {
            Thread threadCurrentThread = Thread.currentThread();
            if (this.threadRef.get() == threadCurrentThread) {
                pushNow(defaultHandle);
            } else {
                pushLater(defaultHandle, threadCurrentThread);
            }
        }

        public boolean scavenge() {
            if (scavengeSome()) {
                return true;
            }
            this.prev = null;
            this.cursor = this.head;
            return false;
        }

        public boolean scavengeSome() {
            WeakOrderQueue weakOrderQueue;
            WeakOrderQueue weakOrderQueue2;
            boolean z2;
            WeakOrderQueue weakOrderQueue3;
            WeakOrderQueue weakOrderQueue4 = this.cursor;
            boolean z3 = false;
            if (weakOrderQueue4 == null) {
                weakOrderQueue2 = null;
                weakOrderQueue = this.head;
                if (weakOrderQueue == null) {
                    return false;
                }
            } else {
                weakOrderQueue = weakOrderQueue4;
                weakOrderQueue2 = this.prev;
            }
            while (true) {
                z2 = true;
                if (weakOrderQueue.transfer(this)) {
                    break;
                }
                weakOrderQueue3 = weakOrderQueue.next;
                if (weakOrderQueue.owner.get() == null) {
                    if (weakOrderQueue.hasFinalData()) {
                        while (weakOrderQueue.transfer(this)) {
                            z3 = true;
                        }
                    }
                    if (weakOrderQueue2 != null) {
                        weakOrderQueue2.setNext(weakOrderQueue3);
                    }
                } else {
                    weakOrderQueue2 = weakOrderQueue;
                }
                if (weakOrderQueue3 == null || z3) {
                    break;
                }
                weakOrderQueue = weakOrderQueue3;
            }
            z2 = z3;
            weakOrderQueue = weakOrderQueue3;
            this.prev = weakOrderQueue2;
            this.cursor = weakOrderQueue;
            return z2;
        }

        public synchronized void setHead(WeakOrderQueue weakOrderQueue) {
            weakOrderQueue.setNext(this.head);
            this.head = weakOrderQueue;
        }
    }

    public static final class WeakOrderQueue {
        public static final /* synthetic */ boolean $assertionsDisabled = false;
        public static final WeakOrderQueue DUMMY = new WeakOrderQueue();
        private final Head head;
        private final int id;
        private WeakOrderQueue next;
        private final WeakReference<Thread> owner;
        private Link tail;

        public static final class Head implements Runnable {
            public static final /* synthetic */ boolean $assertionsDisabled = false;
            private final AtomicInteger availableSharedCapacity;
            public Link link;

            public Head(AtomicInteger atomicInteger) {
                this.availableSharedCapacity = atomicInteger;
            }

            public static boolean reserveSpace(AtomicInteger atomicInteger, int i2) {
                int i3;
                do {
                    i3 = atomicInteger.get();
                    if (i3 < i2) {
                        return false;
                    }
                } while (!atomicInteger.compareAndSet(i3, i3 - i2));
                return true;
            }

            public void reclaimSpace(int i2) {
                this.availableSharedCapacity.addAndGet(i2);
            }

            public boolean reserveSpace(int i2) {
                return reserveSpace(this.availableSharedCapacity, i2);
            }

            @Override // java.lang.Runnable
            public void run() {
                Link link = this.link;
                while (link != null) {
                    reclaimSpace(Recycler.LINK_CAPACITY);
                    link = this.link.next;
                }
            }
        }

        public static final class Link extends AtomicInteger {
            private final DefaultHandle<?>[] elements = new DefaultHandle[Recycler.LINK_CAPACITY];
            public Link next;
            private int readIndex;
        }

        private WeakOrderQueue() {
            this.id = Recycler.ID_GENERATOR.getAndIncrement();
            this.owner = null;
            this.head = new Head(null);
        }

        private WeakOrderQueue(Stack<?> stack, Thread thread) {
            this.id = Recycler.ID_GENERATOR.getAndIncrement();
            this.tail = new Link();
            Head head = new Head(stack.availableSharedCapacity);
            this.head = head;
            head.link = this.tail;
            this.owner = new WeakReference<>(thread);
        }

        public static WeakOrderQueue allocate(Stack<?> stack, Thread thread) {
            if (Head.reserveSpace(stack.availableSharedCapacity, Recycler.LINK_CAPACITY)) {
                return newQueue(stack, thread);
            }
            return null;
        }

        public static WeakOrderQueue newQueue(Stack<?> stack, Thread thread) {
            WeakOrderQueue weakOrderQueue = new WeakOrderQueue(stack, thread);
            stack.setHead(weakOrderQueue);
            ObjectCleaner.register(weakOrderQueue, weakOrderQueue.head);
            return weakOrderQueue;
        }

        /* JADX INFO: Access modifiers changed from: private */
        public void setNext(WeakOrderQueue weakOrderQueue) {
            this.next = weakOrderQueue;
        }

        public void add(DefaultHandle<?> defaultHandle) {
            ((DefaultHandle) defaultHandle).lastRecycledId = this.id;
            Link link = this.tail;
            int i2 = link.get();
            if (i2 == Recycler.LINK_CAPACITY) {
                if (!this.head.reserveSpace(Recycler.LINK_CAPACITY)) {
                    return;
                }
                Link link2 = new Link();
                link.next = link2;
                this.tail = link2;
                i2 = link2.get();
                link = link2;
            }
            link.elements[i2] = defaultHandle;
            ((DefaultHandle) defaultHandle).stack = null;
            link.lazySet(i2 + 1);
        }

        public boolean hasFinalData() {
            return this.tail.readIndex != this.tail.get();
        }

        public boolean transfer(Stack<?> stack) {
            Link link = this.head.link;
            if (link == null) {
                return false;
            }
            if (link.readIndex == Recycler.LINK_CAPACITY) {
                link = link.next;
                if (link == null) {
                    return false;
                }
                this.head.link = link;
            }
            int i2 = link.readIndex;
            int iMin = link.get();
            int i3 = iMin - i2;
            if (i3 == 0) {
                return false;
            }
            int i4 = ((Stack) stack).size;
            int i5 = i3 + i4;
            if (i5 > ((Stack) stack).elements.length) {
                iMin = Math.min((stack.increaseCapacity(i5) + i2) - i4, iMin);
            }
            if (i2 == iMin) {
                return false;
            }
            DefaultHandle<?>[] defaultHandleArr = link.elements;
            DefaultHandle[] defaultHandleArr2 = ((Stack) stack).elements;
            while (i2 < iMin) {
                DefaultHandle<?> defaultHandle = defaultHandleArr[i2];
                if (((DefaultHandle) defaultHandle).recycleId == 0) {
                    ((DefaultHandle) defaultHandle).recycleId = ((DefaultHandle) defaultHandle).lastRecycledId;
                } else if (((DefaultHandle) defaultHandle).recycleId != ((DefaultHandle) defaultHandle).lastRecycledId) {
                    throw new IllegalStateException("recycled already");
                }
                defaultHandleArr[i2] = null;
                if (!stack.dropHandle(defaultHandle)) {
                    ((DefaultHandle) defaultHandle).stack = stack;
                    defaultHandleArr2[i4] = defaultHandle;
                    i4++;
                }
                i2++;
            }
            if (iMin == Recycler.LINK_CAPACITY && link.next != null) {
                this.head.reclaimSpace(Recycler.LINK_CAPACITY);
                this.head.link = link.next;
            }
            link.readIndex = iMin;
            if (((Stack) stack).size == i4) {
                return false;
            }
            ((Stack) stack).size = i4;
            return true;
        }
    }

    static {
        InternalLogger internalLoggerFactory = InternalLoggerFactory.getInstance((Class<?>) Recycler.class);
        logger = internalLoggerFactory;
        NOOP_HANDLE = new Handle() { // from class: io.netty.util.Recycler.1
            @Override // io.netty.util.Recycler.Handle
            public void recycle(Object obj) {
            }
        };
        AtomicInteger atomicInteger = new AtomicInteger(Integer.MIN_VALUE);
        ID_GENERATOR = atomicInteger;
        OWN_THREAD_ID = atomicInteger.getAndIncrement();
        int i2 = SystemPropertyUtil.getInt("io.netty.recycler.maxCapacityPerThread", SystemPropertyUtil.getInt("io.netty.recycler.maxCapacity", 4096));
        int i3 = i2 >= 0 ? i2 : 4096;
        DEFAULT_MAX_CAPACITY_PER_THREAD = i3;
        int iMax = Math.max(2, SystemPropertyUtil.getInt("io.netty.recycler.maxSharedCapacityFactor", 2));
        MAX_SHARED_CAPACITY_FACTOR = iMax;
        MAX_DELAYED_QUEUES_PER_THREAD = Math.max(0, SystemPropertyUtil.getInt("io.netty.recycler.maxDelayedQueuesPerThread", NettyRuntime.availableProcessors() * 2));
        int iSafeFindNextPositivePowerOfTwo = MathUtil.safeFindNextPositivePowerOfTwo(Math.max(SystemPropertyUtil.getInt("io.netty.recycler.linkCapacity", 16), 16));
        LINK_CAPACITY = iSafeFindNextPositivePowerOfTwo;
        int iSafeFindNextPositivePowerOfTwo2 = MathUtil.safeFindNextPositivePowerOfTwo(SystemPropertyUtil.getInt("io.netty.recycler.ratio", 8));
        RATIO = iSafeFindNextPositivePowerOfTwo2;
        if (internalLoggerFactory.isDebugEnabled()) {
            if (i3 == 0) {
                internalLoggerFactory.debug("-Dio.netty.recycler.maxCapacityPerThread: disabled");
                internalLoggerFactory.debug("-Dio.netty.recycler.maxSharedCapacityFactor: disabled");
                internalLoggerFactory.debug("-Dio.netty.recycler.linkCapacity: disabled");
                internalLoggerFactory.debug("-Dio.netty.recycler.ratio: disabled");
            } else {
                internalLoggerFactory.debug("-Dio.netty.recycler.maxCapacityPerThread: {}", Integer.valueOf(i3));
                internalLoggerFactory.debug("-Dio.netty.recycler.maxSharedCapacityFactor: {}", Integer.valueOf(iMax));
                internalLoggerFactory.debug("-Dio.netty.recycler.linkCapacity: {}", Integer.valueOf(iSafeFindNextPositivePowerOfTwo));
                internalLoggerFactory.debug("-Dio.netty.recycler.ratio: {}", Integer.valueOf(iSafeFindNextPositivePowerOfTwo2));
            }
        }
        INITIAL_CAPACITY = Math.min(i3, 256);
        DELAYED_RECYCLED = new FastThreadLocal<Map<Stack<?>, WeakOrderQueue>>() { // from class: io.netty.util.Recycler.3
            @Override // io.netty.util.concurrent.FastThreadLocal
            public Map<Stack<?>, WeakOrderQueue> initialValue() {
                return new WeakHashMap();
            }
        };
    }

    public Recycler() {
        this(DEFAULT_MAX_CAPACITY_PER_THREAD);
    }

    public Recycler(int i2) {
        this(i2, MAX_SHARED_CAPACITY_FACTOR);
    }

    public Recycler(int i2, int i3) {
        this(i2, i3, RATIO, MAX_DELAYED_QUEUES_PER_THREAD);
    }

    public Recycler(int i2, int i3, int i4, int i5) {
        this.threadLocal = new FastThreadLocal<Stack<T>>() { // from class: io.netty.util.Recycler.2
            @Override // io.netty.util.concurrent.FastThreadLocal
            public Stack<T> initialValue() {
                return new Stack<>(Recycler.this, Thread.currentThread(), Recycler.this.maxCapacityPerThread, Recycler.this.maxSharedCapacityFactor, Recycler.this.ratioMask, Recycler.this.maxDelayedQueuesPerThread);
            }

            @Override // io.netty.util.concurrent.FastThreadLocal
            public void onRemoval(Stack<T> stack) {
                if (stack.threadRef.get() == Thread.currentThread() && Recycler.DELAYED_RECYCLED.isSet()) {
                    ((Map) Recycler.DELAYED_RECYCLED.get()).remove(stack);
                }
            }
        };
        this.ratioMask = MathUtil.safeFindNextPositivePowerOfTwo(i4) - 1;
        if (i2 <= 0) {
            this.maxCapacityPerThread = 0;
            this.maxSharedCapacityFactor = 1;
            this.maxDelayedQueuesPerThread = 0;
        } else {
            this.maxCapacityPerThread = i2;
            this.maxSharedCapacityFactor = Math.max(1, i3);
            this.maxDelayedQueuesPerThread = Math.max(0, i5);
        }
    }

    public final T get() {
        if (this.maxCapacityPerThread == 0) {
            return newObject(NOOP_HANDLE);
        }
        Stack<T> stack = this.threadLocal.get();
        DefaultHandle<T> defaultHandlePop = stack.pop();
        if (defaultHandlePop == null) {
            defaultHandlePop = stack.newHandle();
            ((DefaultHandle) defaultHandlePop).value = newObject(defaultHandlePop);
        }
        return (T) ((DefaultHandle) defaultHandlePop).value;
    }

    public abstract T newObject(Handle<T> handle);

    @Deprecated
    public final boolean recycle(T t2, Handle<T> handle) {
        if (handle == NOOP_HANDLE) {
            return false;
        }
        DefaultHandle defaultHandle = (DefaultHandle) handle;
        if (defaultHandle.stack.parent != this) {
            return false;
        }
        defaultHandle.recycle(t2);
        return true;
    }

    public final int threadLocalCapacity() {
        return ((Stack) this.threadLocal.get()).elements.length;
    }

    public final int threadLocalSize() {
        return ((Stack) this.threadLocal.get()).size;
    }
}
