All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.voovan.tools.collection.ThreadObjectPool Maven / Gradle / Ivy

There is a newer version: 4.3.8
Show newest version
package org.voovan.tools.collection;

import org.voovan.tools.FastThreadLocal;

import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 线程对象池
 *
 * @author: helyho
 * Voovan Framework.
 * WebSite: https://github.com/helyho/Voovan
 * Licence: Apache v2 License
 */
public class ThreadObjectPool {
    private FastThreadLocal> threadLocalPool;

    private int threadPoolSize = 64;

    public ThreadObjectPool() {
    }

    public ThreadObjectPool(int threadPoolSize) {
        this.threadPoolSize = threadPoolSize;
        threadLocalPool =  FastThreadLocal.withInitial(()->new RingBuffer(this.threadPoolSize));
    }


    public ThreadObjectPool(int threadPoolSize, Supplier supplier) {
        this.threadPoolSize = threadPoolSize;
        threadLocalPool =  FastThreadLocal.withInitial(()->{
            RingBuffer ringBuffer = new RingBuffer(this.threadPoolSize);
            for(int i = 0; i< threadPoolSize; i++) {
                ringBuffer.push(supplier.get());
            }
            return ringBuffer;
        });
    }


    public int getThreadPoolSize() {
        return threadPoolSize;
    }

    public RingBuffer getPool(){
        return threadLocalPool.get();
    }

    public T get(Supplier supplier){
        RingBuffer pool = getPool();

        T t = pool.pop();

        //创建一个新的 t
        if(t==null) {
            t = (T) supplier.get();
        }

        return t;
    }

    public void release(T t, Consumer destory){
        RingBuffer pool = getPool();

        //如果小于线程中池的大小则放入线程中的池
        if(!pool.push(t)) {
            destory.accept(t);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy