!792 【轻量级pr】优化 getProcessorCount 潜在的获取不到的问题 - V5

Merge pull request !792 from dazer007/v5-dev-cpunum-fix
This commit is contained in:
Looly 2022-09-04 16:39:25 +00:00 committed by Gitee
commit 84b4609d43
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
4 changed files with 24 additions and 3 deletions

View File

@ -1,5 +1,7 @@
package cn.hutool.core.thread;
import cn.hutool.core.util.RuntimeUtil;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
@ -126,7 +128,7 @@ public class ThreadUtil {
}
// 最佳的线程数 = CPU可用核心数 / (1 - 阻塞系数)
int poolSize = (int) (Runtime.getRuntime().availableProcessors() / (1 - blockingCoefficient));
int poolSize = (int) (RuntimeUtil.getProcessorCount() / (1 - blockingCoefficient));
return ExecutorBuilder.create().setCorePoolSize(poolSize).setMaxPoolSize(poolSize).setKeepAliveTime(0L).build();
}

View File

@ -13,6 +13,7 @@ import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 系统运行时工具类用于执行系统命令的工具
@ -234,11 +235,21 @@ public class RuntimeUtil {
/**
* 获得JVM可用的处理器数量一般为CPU核心数
*
* <p>
* 这里做一个特殊的处理,在特殊的CPU上面会有获取不到CPU数量的情况所以这里做一个保护;
* 默认给一个7真实的CPU基本都是偶数方便区分
* 如果不做处理会出现创建线程池时{@link ThreadPoolExecutor}抛出异常{@link IllegalArgumentException}
* </p>
*
* @return 可用的处理器数量
* @since 5.3.0
*/
public static int getProcessorCount() {
return Runtime.getRuntime().availableProcessors();
int cpu = Runtime.getRuntime().availableProcessors();
if (cpu <= 0) {
cpu = 7;
}
return cpu;
}
/**

View File

@ -43,4 +43,11 @@ public class RuntimeUtilTest {
int pid = RuntimeUtil.getPid();
Assert.assertTrue(pid > 0);
}
@Test
public void getProcessorCountTest(){
int cpu = RuntimeUtil.getProcessorCount();
Console.log("cpu个数{}", cpu);
Assert.assertTrue(cpu > 0);
}
}

View File

@ -2,6 +2,7 @@ package cn.hutool.socket.aio;
import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import java.io.IOException;
@ -12,7 +13,7 @@ import java.nio.channels.AsynchronousChannelGroup;
public class AioClientTest {
public static void main(String[] args) throws IOException {
final AsynchronousChannelGroup GROUP = AsynchronousChannelGroup.withFixedThreadPool(//
Runtime.getRuntime().availableProcessors(), // 默认线程池大小
RuntimeUtil.getProcessorCount(), // 默认线程池大小
ThreadFactoryBuilder.create().setNamePrefix("Huool-socket-").build()//
);