gpt4 book ai didi

java - 我如何控制垃圾收集器?

转载 作者:行者123 更新时间:2023-11-29 04:12:33 25 4
gpt4 key购买 nike

所以我正在编写一种算法,与我同学的算法玩棋盘游戏。它基本上预见了游戏的每一种可能结果,并根据每条路径的获胜百分比选择最佳路径。在游戏中,每个玩家有 5 秒的时间来采取行动。因为它都在一台 PC 上运行,所以我不能在我的对手移动过程中使用处理能力或太多的内存空间。

我正在使用树结构,每个节点如下所示:

public class Node {

//coordinates on the board
private Move move;
//winpercentage for choosing this path
private double winPercentage;
//is this move mine to make or is it opponents (the last person to make a move wins the game)
private boolean odd;
//all possible next moves
private Set<Node> children;
//previous move
private Node parent;
}

我正在使用一个包装类 Tree,它包含树的根和一些用于遍历和构建结构的方法。

public class Tree {

Node root;


public Tree() {
this.root = Node.createRoot();
}

//methods to traverse/build the tree
}

即使在我构建了整棵树并选择了我的移动之后,树仍会在我的对手移动期间存储在内存中,这是被禁止的,因为当我占用 4GB RAM 时他无法移动。我已经尝试将引用设置为 null 以触发 GC,但它似乎不起作用

} else if(input.equals("tree")){
System.out.println("Showing tree structure");
Tree tree = new Tree();
//does all the work
tree.mainFunctionWrapper(tree.getRoot());
tree.setRoot(null);
tree = null;
}

因为它全部在一个代码块中,所以我没有进一步或以前对树结构的引用。

如何让垃圾收集器工作或手动释放内存?

最佳答案

您不能自己触发 GC,因为 System.gc() 只是一个提示。执行 tree = null; 将删除引用,但是 Tree 对象仍然分配在堆中,直到 GC 决定删除它。

最好的办法是改进您的代码,使其不需要 4 GB 的堆内存,并使用 -Xmx2g 或类似选项来限制 JVM。根据 this answer JVM 并不热衷于将内存返回给系统。它可能会发生,但不是每 5 秒就可以完成的事情。

关于java - 我如何控制垃圾收集器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173585/

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