mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
修复availableProcessors,潜在的native方法获取CPU个数失败的问题
This commit is contained in:
parent
4a0a977397
commit
97174e2ffc
@ -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;
|
||||
@ -129,7 +131,7 @@ public class ThreadUtil {
|
||||
}
|
||||
|
||||
// 最佳的线程数 = CPU可用核心数 / (1 - 阻塞系数)
|
||||
final int poolSize = (int) (Runtime.getRuntime().availableProcessors() / (1 - blockingCoefficient));
|
||||
final int poolSize = (int) (RuntimeUtil.getProcessorCount() / (1 - blockingCoefficient));
|
||||
return ExecutorBuilder.of().setCorePoolSize(poolSize).setMaxPoolSize(poolSize).setKeepAliveTime(0L).build();
|
||||
}
|
||||
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -43,4 +43,11 @@ public class RuntimeUtilTest {
|
||||
final int pid = RuntimeUtil.getPid();
|
||||
Assert.assertTrue(pid > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getProcessorCountTest(){
|
||||
int cpu = RuntimeUtil.getProcessorCount();
|
||||
Console.log("cpu个数:{}", cpu);
|
||||
Assert.assertTrue(cpu > 0);
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user