Skip to content

Instantly share code, notes, and snippets.

@c-rainstorm
Created October 29, 2020 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c-rainstorm/88735daa513b9794c4f0a44bd47a7124 to your computer and use it in GitHub Desktop.
Save c-rainstorm/88735daa513b9794c4f0a44bd47a7124 to your computer and use it in GitHub Desktop.
通用的异步执行工具
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
@Slf4j
public class AsyncUtil {
/**
* 异步场景 -> 线程池
*/
private static final ConcurrentMap<AsyncScene, ExecutorService> threadPoolCacheMap
= new ConcurrentHashMap<>(128);
static {
for (AsyncScene scene : AsyncScene.values()) {
ThreadPoolExecutor executorService = new ThreadPoolExecutor(scene.corePoolSize, scene.maximumPoolSize,
scene.keepAliveTime, scene.unit, scene.workQueue, scene.threadFactory, scene.handler);
executorService.allowCoreThreadTimeOut(true);
threadPoolCacheMap.put(scene, executorService);
}
}
public static void run(Runnable runnable) {
run(runnable, AsyncScene.COMMON);
}
public static void run(Runnable runnable, AsyncScene asyncScene) {
if (asyncScene == null) {
asyncScene = AsyncScene.COMMON;
}
CompletableFuture.runAsync(() -> {
try {
runnable.run();
} catch (Throwable t) {
log.error(t.getMessage(), t);
}
}, threadPoolCacheMap.get(asyncScene));
}
public static ExecutorService get(AsyncScene scene) {
return threadPoolCacheMap.get(scene);
}
public enum AsyncScene {
/**
* 通用场景
*/
COMMON,
AsyncScene() {
this(Runtime.getRuntime().availableProcessors() * 2, 64, 60, TimeUnit.SECONDS, 1000, new ThreadPoolExecutor.CallerRunsPolicy());
}
AsyncScene(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, int workQueueCapacity, RejectedExecutionHandler handler) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.keepAliveTime = keepAliveTime;
this.unit = unit;
this.workQueue = new LinkedBlockingQueue<>(workQueueCapacity);
this.threadFactory = new ThreadFactoryBuilder().setNameFormat(String.format("async-scene-%s-%%d", this.name().toLowerCase())).build();
this.handler = handler;
}
int corePoolSize;
int maximumPoolSize;
long keepAliveTime;
TimeUnit unit;
BlockingQueue<Runnable> workQueue;
ThreadFactory threadFactory;
RejectedExecutionHandler handler;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment