因此,我正在编写一种算法,该算法针对我的同学算法玩一种棋盘游戏。它基本上预见了游戏的所有可能结果,并根据采用每种方法的获胜率选择最佳方法。在游戏中,每个玩家有5秒的动作时间。由于它们全部运行在一台PC上,因此我在对手移动时无法使用处理能力或过多的内存空间。
我正在使用一个Tree结构,每个节点如下所示:
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;
}
由于它全部在一个代码块中,因此我没有对树结构的进一步引用或以前的引用。
如何使垃圾收集器工作或手动释放内存?
答案 0 :(得分:3)
您不能自己触发GC,因为System.gc()
只是一个提示。进行tree = null;
会删除引用,但是Tree
对象仍然分配在堆中,直到GC决定删除它为止。
您最好的选择是将代码改进为不需要4 GB的堆内存,并使用-Xmx2g
或类似选项来限制JVM。根据{{3}},JVM不希望将内存返回给系统。它可以发生,但不是每5秒就可以完成一次。