gpt4 book ai didi

java - 异常: java. lang.OutOfMemoryError,无法创建新的 native 线程

转载 作者:行者123 更新时间:2023-12-01 04:35:50 24 4
gpt4 key购买 nike

我每 5 秒创建一个新线程,并使用Threadpool exector。我确保线程正在关闭。但我越来越

线程“Timer-0”中出现异常 java.lang.OutOfMemoryError:无法创建新的 native 线程。

发生这种情况是因为我创建了许多线程并且没有关闭它们吗?或者经常创建新的?

如果我在代码中做错了什么,有人可以告诉我吗?

public class API{
private MongoStoreExecutor executor = new MongoStoreExecutor(10,50);
private class MongoStoreExecutor extends ThreadPoolExecutor {
public MongoStoreExecutor(int queueSize, int maxThreadPoolSize) {
super(10, maxThreadPoolSize, 30, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(queueSize),
new ThreadPoolExecutor.CallerRunsPolicy());
}
}

public TimerTask alertingPoolsData() throws Exception, UnknownHostException {
TimeerTask task = new TimerTask(){
public void run(){
Pools = alertingPools.values().toArray();
List<Future<?>> tasks = new ArrayList<Future<?>>(Pools.length);
for (Object pool : Pools) {
tasks.add(executor.submit(new DataAccumulation(timeStartSecData,
timeEndSec,pool, jsonArrayResult,dataResult)));
}
for( Future<?> f: tasks) {
f.get(2 * 1000L, TimeUnit.MILLISECONDS);
}
}
} catch (Exception e) {
e.printStackTrace();
}

long interval = 5 * 1000L;
tm.scheduleAtFixedRate(task,(interval -
(System.currentTimeMillis() % interval)), interval);
return task;
}
}

最佳答案

我的预感与我们看不到的代码有关:我怀疑您正在调用 alertingPoolsData一次又一次地在某个地方。因此,我怀疑您正在安排TimerTask一遍又一遍地。这些组件中的每一个 TimerTasks然后重复创建一些未知数量的 Future<?>s ( Pools 的每个元素都有一个),每个元素都会指向您的 MongoStoreExecutor .

如果上述所有情况均成立,则线程数曲线上的一阶导数为正。因此,随着时间的推移,您将看到线程数呈二次方增加。您将开始点击 upper limits of your native threads很快。

正如评论中所建议的,您可以轻松修改当前的实现。我建议 ScheduledExecutorService 的组合和一个ForkJoinPool .

关于java - 异常: java. lang.OutOfMemoryError,无法创建新的 native 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17377627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com