import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import java.util.concurrent.*;
@Import({SpringUtil.class})
@Configuration
@Slf4j
public class ThreadPoolConfig {
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
@Bean(value = "executorService")
public ThreadPoolExecutor threadPoolExecutor() {
ThreadPoolExecutor executor = new TraceThreadPoolExecutor(
CPU_COUNT,
CPU_COUNT * 2 + 1,
30L,
TimeUnit.SECONDS,
new LinkedBlockingQueue(100000),
Executors.defaultThreadFactory(),
new BusinessAbortPolicy()) {
@Override
protected void beforeExecute(Thread t, Runnable r) {
log.info("Thread ready to execute:{}", t.getName());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (t == null) {
log.info("Thread execution complete:{}", new Thread(r).getName());
} else {
log.error("Thread execution exception{}--->{}", new Thread(r).getName(), t.getMessage());
}
}
@Override
protected void terminated() {
log.info("Thread pool exit");
}
};
return executor;
}
}
class BusinessAbortPolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
Log log = Log.get();
String message = "任务 " + r.toString() + " 被 " + executor.toString() + "拒绝!!";
log.error("The_thread_pool_is_full and cannot continue processing tasks>>>>{}", message);
}
}
class TraceThreadPoolExecutor extends ThreadPoolExecutor {
public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
public void execute(Runnable command) {
super.execute(wrap(command, clientTrace(), Thread.currentThread().getName()));
}
@Override
public Future<?> submit(Runnable task) {
return super.submit(wrap(task, clientTrace(), Thread.currentThread().getName()));
}
private Exception clientTrace() {
return new Exception("============Client_thread_exception=================");
}
private Runnable wrap(final Runnable task, final Exception clientStack, String clientThreadName) {
return new Runnable() {
@Override
public void run() {
try {
task.run();
} catch (Exception ex) {
clientStack.printStackTrace();
throw ex;
}
}
};
}
}
//使用
CompletableFuture.runAsync(() -> {
doSomething
}, executorService);原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。