org.voovan.tools.collection.ThreadObjectPool Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of voovan-common Show documentation
Show all versions of voovan-common Show documentation
Voovan is a java framwork and it not depends on any third-party framework.
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);
}
}
}