8-puzzle java.lang.OutOfMemoryError:超出了GC开销限制

时间:2013-11-18 15:19:04

标签: java garbage-collection out-of-memory

当我运行我的8-puzzle程序时,我一直在“超出GC开销限制”。我曾尝试为JVM添加更多内存,但这没有帮助。

这是问题的方法:

    public void search() {
    addToQueue(start, null);// add root
    while (!queue.isEmpty()) {
        currState = queue.removeFirst();


        if (goal.equals(currState)) { 
            solution = true;
            printSolution(currState);
            break;

        } else {
            a = currState.indexOf("0");

            // left
            while (a != 0 && a != 3 && a != 6) {

                String nextState = currState.substring(0, a - 1) + "0"
                        + currState.charAt(a - 1)
                        + currState.substring(a + 1);
                addToQueue(nextState, currState);
                nodes++;
                break;
            }
            // up
            while (a != 0 && a != 1 && a != 2) {

                String nextState = currState.substring(0, a - 3) + "0"
                        + currState.substring(a - 2, a)
                        + currState.charAt(a - 3)
                        + currState.substring(a + 1);
                addToQueue(nextState, currState);
                nodes++;
                break;
            }
            // right
            while (a != 2 && a != 5 && a != 8) {

                String nextState = currState.substring(0, a)
                        + currState.charAt(a + 1) + "0"
                        + currState.substring(a + 2)
                        + currState.substring(a + 1);
                addToQueue(nextState, currState);
                nodes++;
                break;
            }
            // down
            while (a != 6 && a != 7 && a != 8) {

                String nextState = currState.substring(0, a)
                        + currState.substring(a + 3, a + 4)
                        + currState.substring(a + 1, a + 3) + "0"
                        + currState.substring(a + 4);
                addToQueue(nextState, currState);
                nodes++;
                break;
            }

        }

    }

}

Start是我从文件.txt读入的String。 它可以解决一些问题,但有些会产生这个错误。

    private void addToQueue(String newState, String oldState) {
    if (!levelDepth.containsKey(newState)) {
        newValue = oldState == null ? 0 : levelDepth.get(oldState) + 1;
        unique++;
        levelDepth.put(newState, newValue);
        queue.add(newState);
        stateHistory.put(newState, oldState);

    }

}

1 个答案:

答案 0 :(得分:2)

您得到的错误是由于GC线程占用了98%或更多的处理器时间。

最简单的方法是将方法分解为几种不同的方法,这样就可以收集方法本地字符串。

其次使用StringBuffers进行连接,字符串连接将大大减慢速度。

还有其他一些你可以解决的事情,并发GC等,但帮助你的方法结构是最重要的。