cn.tom.kit.ThreadPool Maven / Gradle / Ivy
The newest version!
package cn.tom.kit;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 线程池
*/
public class ThreadPool {
private ThreadPoolExecutor executor;
public ThreadPool(String name, int coreSize) { // 开放动态的 线程pool 作为特例优化
executor = new ThreadPoolExecutor(coreSize, coreSize, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue(), new DefaultThreadFactory(name));
// 设置allowCoreThreadTimeOut,允许回收超时的线程
//executor.allowCoreThreadTimeOut(true); // true 回收, false 不回收
}
public void execute(Runnable command) {
if(executor !=null && !executor.isShutdown()){
executor.execute(command);
}
}
public void shutdown(){
executor.shutdown();
}
public ThreadPoolExecutor getExecutor(){
return executor;
}
public static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
public DefaultThreadFactory() {
this("cocook-comm-pool-");
}
public DefaultThreadFactory(String poolname) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = poolname + poolNumber.getAndIncrement() + "-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
/**
* 创建固定大小的阻塞线程池
* @param size
* @return
* 注意, 直接阻塞的 是 execute 方法, 不是在内部阻塞
* @deprecated
*/
public static ThreadPoolExecutor createBlockPool(int size) { //
ThreadPoolExecutor threadPoolInstance = new ThreadPoolExecutor(cpuCoreCount*2 , cpuCoreCount*10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(size),
new DefaultThreadFactory("cocook-block-pool-"), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// 会阻塞整个execute 方法 不建议使用
logger.warn("CommPool querysize: {}, execNum: {}", executor.getQueue().size(),
executor.getActiveCount());
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
// 设置allowCoreThreadTimeOut,允许回收超时的线程
threadPoolInstance.allowCoreThreadTimeOut(true);
return threadPoolInstance;
}
/**
* 超出线程queue 忽略的线程
* @param size
* @return
*/
public static ThreadPoolExecutor createDiscardPool(int size) { //
ThreadPoolExecutor threadPoolInstance = new ThreadPoolExecutor(cpuCoreCount*2 , cpuCoreCount*10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(size),
new DefaultThreadFactory("cocook-discard-pool-"), new ThreadPoolExecutor.DiscardPolicy());
// 设置allowCoreThreadTimeOut,允许回收超时的线程
threadPoolInstance.allowCoreThreadTimeOut(true);
return threadPoolInstance;
}
/**
* 返回公用线程池
*
* @return 公用线程池
*/
public static ThreadPool getCommPool() {
if (commPool == null || commPool.getExecutor().isShutdown()) {
synchronized (lock) {
if(commPool == null){
commPool = new ThreadPool("CommPool-", cpuCoreCount*2);
}
}
}
return commPool;
}
public static ThreadPool getAioPool() {
if (aioPool == null || aioPool.getExecutor().isShutdown()) {
synchronized (lock) {
if (aioPool == null) {
aioPool = new ThreadPool("AioPool-", cpuCoreCount*2);
}
}
}
return aioPool;
}
public static void exec(Runnable command) {
getCommPool().execute(command);
}
public static int cpuCoreCount = Runtime.getRuntime().availableProcessors();
private static Logger logger = LoggerFactory.getLogger(ThreadPool.class);
private static Object lock = new Object();
private static volatile ThreadPool commPool ;
private static volatile ThreadPool aioPool;
}