gpt4 book ai didi

java - 使用以下递归方法时出现 java.lang.OutOfMemoryError 异常

转载 作者:行者123 更新时间:2023-12-01 06:03:11 25 4
gpt4 key购买 nike

enter image description here基本上,下面的方法是遍历节点并创建类似图形的结构。创建超过 400K 对象会导致 OutOfMemoryError。有人可以帮忙优化下面的代码吗?

方法:

    private static PolicyNodeInfo[] mapPolicySteps(PolicyTreatmentNodeInfo fromObj)
{

List<PolicyNodeInfo> tmpList = new ArrayList<PolicyNodeInfo>();
PolicyTreatmentNodeInfo[] childrens = fromObj.getChildrenPolicyInfo();
// Get object policy node children

if(childrens != null) //if there are no children return empty list
{
for(PolicyTreatmentNodeInfo child : childrens)
//for each children map the object and recursively go over his children
{
if(null!=child)
{
if(X3ServerUtil.isStringNotEmptyNotNull(child.getStepName())&&
!child.getStepName().startsWith("Dummy"))
//case child is not null (edge) or it's not non operation step (need to ignore)
{
int index = tmpList.size();
tmpList.add(insertStep(child)); //insert current node

tmpList.get(index).setPolicyTreatmentNodeInfoList(mapPolicySteps(child));
//insert recursively all child nodes
}
else
{
handleDummyChildNodeInsertion(tmpList, child);
}
}
}
}
return tmpList.toArray(new PolicyNodeInfo[tmpList.size()]);
}

Exception : (Stack.java:23) weblogic.kernel.ThreadLocalStack$StackInitialValue.initialValue(ThreadLocalStack.java:159) at weblogic.kernel.FinalThreadLocal$FinalThreadStorage.(FinalThreadLocal.java:208) at weblogic.kernel.AuditableThread.(AuditableThread.java:13) Truncated. see log file for complete stacktrace

图结构与下图类似,有 49 个节点。并且由于可能有多个路径,该方法被调用超过 400K 次..

最佳答案

递归对于遍历大数据集是危险的,因为堆栈内存实际上不受您的控制。 (换句话说:我在学校学到的递归是一种“最优雅”的解决方案,而在大学里却被认为是“不要这样做”——想想看……)

为了消除这种情况,请使用合适的数据结构来展开,例如沿着这些线的队列:

Deque<MyObject> queue = ...
queue.push(rootElement);
while (!queue.isEmpty()) {
MyObject currentElement = queue.poll();
// ... process current element
// and in the end: push children
currentElement.getChildren().forEach(child -> queue.push(child));
}

对于深度优先遍历,请使用堆栈(即 pop() 而不是 poll());

如果这仍然给您带来内存不足错误,您要么必须增加堆空间,要么使用不同的方法。

关于java - 使用以下递归方法时出现 java.lang.OutOfMemoryError 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52178012/

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