feat: 状态机内置默认用于异步执行事件的线程池.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package com.serliunx.statemanagement.machine;
|
||||
|
||||
import com.serliunx.statemanagement.machine.handler.StateHandlerWrapper;
|
||||
import com.serliunx.statemanagement.support.ExecutorUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -51,8 +52,18 @@ public final class StateMachineContext<S> {
|
||||
this.entryHandlers = entryHandlers;
|
||||
this.leaveHandlers = leaveHandlers;
|
||||
this.exchangeHandlers = exchangeHandlers;
|
||||
this.executor = executor;
|
||||
this.executor = executorAutoConfiguration(executor);
|
||||
this.async = async;
|
||||
this.eventRegistries = eventRegistries;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行器为空时自动创建一个适合当前操作系统的执行器(线程池)
|
||||
*/
|
||||
private Executor executorAutoConfiguration(Executor source) {
|
||||
if (source == null) {
|
||||
return ExecutorUtils.adaptiveThreadPool();
|
||||
}
|
||||
return source;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package com.serliunx.statemanagement.support;
|
||||
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 线程池相关工具类
|
||||
*
|
||||
* @author <a href="mailto:serliunx@yeah.net">SerLiunx</a>
|
||||
* @version 1.0.0
|
||||
* @since 2024/12/28
|
||||
@@ -8,4 +15,17 @@ package com.serliunx.statemanagement.support;
|
||||
public final class ExecutorUtils {
|
||||
|
||||
private ExecutorUtils() {throw new UnsupportedOperationException();}
|
||||
|
||||
/**
|
||||
* 快速获取自适应参数的线程池
|
||||
* <li> 核心线程数量为当前处理器数量的两倍; 最大线程数量为当前处理器数量的四倍.
|
||||
*
|
||||
* @return 执行器(线程池)
|
||||
*/
|
||||
public static Executor adaptiveThreadPool() {
|
||||
final int processors = Runtime.getRuntime().availableProcessors();
|
||||
return new ThreadPoolExecutor(processors * 2, processors * 4, 5,
|
||||
TimeUnit.MINUTES, new ArrayBlockingQueue<>(processors * 8), new NamedThreadFactory("state-process-%s"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.serliunx.statemanagement.support;
|
||||
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* 模板名称线程池
|
||||
*
|
||||
* @author <a href="mailto:serliunx@yeah.net">SerLiunx</a>
|
||||
* @since 2025/2/17
|
||||
*/
|
||||
public final class NamedThreadFactory implements ThreadFactory {
|
||||
|
||||
private final AtomicInteger threadNumber = new AtomicInteger(0);
|
||||
|
||||
private final String namePattern;
|
||||
|
||||
public NamedThreadFactory(String namePattern) {
|
||||
this.namePattern = namePattern;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
return new Thread(r, String.format(namePattern, threadNumber.getAndIncrement()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user