org.voovan.tools.collection.ObjectThreadPool Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of voovan-framework Show documentation
Show all versions of voovan-framework Show documentation
Voovan is a java framwork and it not depends on any third-party framework.
package org.voovan.tools.collection;
import java.util.LinkedList;
import java.util.function.Supplier;
/**
* 类文字命名
*
* @author: helyho
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class ObjectThreadPool {
private final ThreadLocal> THREAD_LOCAL_POOL = ThreadLocal.withInitial(()->new LinkedList());
private int threadLocalMaxSize = 4;
public ObjectThreadPool() {
}
public ObjectThreadPool(int threadLocalMaxSize) {
this.threadLocalMaxSize = threadLocalMaxSize;
}
public int getThreadLocalMaxSize() {
return threadLocalMaxSize;
}
public void setThreadLocalMaxSize(int threadLocalMaxSize) {
this.threadLocalMaxSize = threadLocalMaxSize;
}
public LinkedList getThreadLoaclPool(){
return THREAD_LOCAL_POOL.get();
}
public T get(Supplier supplier){
LinkedList threadLocalPool = getThreadLoaclPool();
T t = threadLocalPool.poll();
//创建一个新的 t
if(t==null) {
t = (T) supplier.get();
}
return t;
}
public void release(T t, Supplier destory){
LinkedList threadLocalPool = getThreadLoaclPool();
//如果小于线程中池的大小则放入线程中的池
if(threadLocalPool.size() < threadLocalMaxSize) {
threadLocalPool.offer(t);
} else {
destory.get();
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy