I am having heap space errors with the below code.
Anybody have any idea how to optimize this code.
This happens for large files [180MB]. The method parameter has around 50 metatag key-values corresponding to each locale. The error shows up after handling 4500 pages.
Note: I tried changing foreach to iterator to use iterator.remove() for freeing up space.
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();
}
From my code I am setting this to a parent properties obj as follows :
UnicodeProperties myParentProps = new UnicodeProperties();
//Set some values to parent
UnicodeProperties myLayoutProps = new UnicodeProperties();
//Set some values to child
....
myParentProps.setProperty("childProp",myChildPropsToString(myLayoutProps));
Any help would be deeply appreciated !
Try putting the propsIterator.remove(); inside the while.