线程池操作工具类
package com.wmang.util;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
public class ThreadPoolProcessor {
static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolProcessor.class);
private static final int DEFAULT_MAX_CONCURRENT = Runtime.getRuntime().availableProcessors() * 20;
private static final String THREAD_POOL_NAME = "ExternalConvertProcessPool-%d";
private static final ThreadFactory FACTORY = new BasicThreadFactory.Builder().namingPattern(THREAD_POOL_NAME)
.daemon(true).build();
private static final int DEFAULT_SIZE = 20000*10;
private static final long DEFAULT_KEEP_ALIVE = 60L;
private static ExecutorService executor;
private static BlockingQueue<Runnable> executeQueue = new ArrayBlockingQueue<>(DEFAULT_SIZE);
static {
try {
executor = new ThreadPoolExecutor(DEFAULT_MAX_CONCURRENT, DEFAULT_MAX_CONCURRENT * 4, DEFAULT_KEEP_ALIVE,
TimeUnit.SECONDS, executeQueue, FACTORY);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
ThreadPoolProcessor.LOGGER.info("ThreadPoolProcessor shutting down.");
executor.shutdown();
try {
if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
ThreadPoolProcessor.LOGGER.error("ThreadPoolProcessor shutdown immediately due to wait timeout.");
executor.shutdownNow();
}
} catch (InterruptedException e) {
ThreadPoolProcessor.LOGGER.error("ThreadPoolProcessor shutdown interrupted.");
executor.shutdownNow();
}
ThreadPoolProcessor.LOGGER.info("ThreadPoolProcessor shutdown complete.");
}
}));
} catch (Exception e) {
LOGGER.error("ThreadPoolProcessor init error.", e);
throw new ExceptionInInitializerError(e);
}
}
private ThreadPoolProcessor() {
}
public static boolean executeTask(Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException e) {
LOGGER.error("Task executing was rejected.", e);
return false;
}
return true;
}
public static <T> Future<T> submitTask(Callable<T> task) {
try {
return executor.submit(task);
} catch (RejectedExecutionException e) {
LOGGER.error("Task executing was rejected.", e);
throw new UnsupportedOperationException("Unable to submit the task, rejected.", e);
}
}
}