堆空间错误 - 如何优化此代码

时间:2012-11-16 17:32:58

标签: java memory-management out-of-memory heap-memory

我使用以下代码堆空间错误

任何人都知道如何优化此代码

对于大文件[180MB]会发生这种情况。方法参数具有与每个区域设置对应的大约50个metatag 键值。处理4500页后会出现错误。

注意:我尝试将 foreach 更改为 iterator 以使用 iterator.remove()< / em>用于释放空间。

public static String myChildPropsToString(final UnicodeProperties myLayoutProps) {       
    final StringBuilder sb = new StringBuilder(myLayoutProps.size());

    final String[] matchTarget = new String[] { StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE, StringPool.RETURN };
    final String[] replaceTargetBy = new String[] { "_SAFE_NEWLINE_CHARACTER_", "_SAFE_NEWLINE_CHARACTER_",
            "_SAFE_NEWLINE_CHARACTER_" };

     //COMMENTED TO TRY OUT ITERATOR.REMOVE
    //
    // for (final Map.Entry<String, String> entry : myLayoutProps.entrySet()) {
    // final String value = entry.getValue();
    //
    // if (Validator.isNotNull(value)) {
    // StringUtil.replace(value, matchTarget, replaceTargetBy);
    //
    // sb.append(entry.getKey());
    // sb.append(StringPool.EQUAL);
    // sb.append(value);
    // sb.append(StringPool.NEW_LINE);
    // }
    // }

    final Iterator<Entry<String, String>> propsIterator = myLayoutProps.entrySet().iterator();
    while (propsIterator.hasNext()) {
        final Entry<String, String> entry = propsIterator.next();

        if (Validator.isNotNull(entry.getValue())) {
            StringUtil.replace(entry.getValue(), matchTarget, replaceTargetBy);

            sb.append(entry.getKey());
            sb.append(StringPool.EQUAL);
            sb.append(entry.getValue());
            sb.append(StringPool.NEW_LINE);
        }
    }
    propsIterator.remove();

    return sb.toString();
}

从我的代码我将其设置为父属性obj,如下所示:

UnicodeProperties myParentProps = new UnicodeProperties();
//Set some values to parent
UnicodeProperties myLayoutProps = new UnicodeProperties();
//Set some values to child
....
myParentProps.setProperty("childProp",myChildPropsToString(myLayoutProps));

任何帮助都将深表感谢!

1 个答案:

答案 0 :(得分:0)

尝试放置propsIterator.remove();在里面。

final Iterator<Entry<String, String>> propsIterator = myLayoutProps.entrySet().iterator();
    while (propsIterator.hasNext()) {
        final Entry<String, String> entry = propsIterator.next();

        if (Validator.isNotNull(entry.getValue())) {
            StringUtil.replace(entry.getValue(), matchTarget, replaceTargetBy);

            sb.append(entry.getKey());
            sb.append(StringPool.EQUAL);
            sb.append(entry.getValue());
            sb.append(StringPool.NEW_LINE);
        }
        propsIterator.remove();
    }