how to avoid outofMemory error due to String variable

Question!

I have big data input xml files which I am parsing using stax parser and then I am storing a set of specific tag values to txt file. I am having 4 cases to check but everytime after 2 nd check its giving outof memory error at

for (String conversa: p_convers) {
    converInfo += conversa + "-----"; 
}

At this line a huge set of paragraph text will be added by many users and then I will store it to file.

To avoid this stage of memory issue I have added VM var arguments at Eclipse as below at Run configuration

-Xms1024m
-Xmx1024m
-XX:MaxPermSize=256m

with this settings it will run successfully with warning message as

Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0

How to avoid these things and use stable code?



Answers

As others have already answered, first replace string concatenation with StringBuilder. If it does not help, change the algorithm.

"At this line a huge set of paragraph text will be added by many users and then I will store it to file. "

Instead of creation of one big buffer, try to write smaller chunks to the file just after reading them.

By : pkalinow




Use StringBuilder/StringBuffer to concatenate strings. If you use then each time you create new string instance e.g. in line from loop you create three strings (lets say in conversa you got 'conversa' value):

  • conversa
  • conversa-----
  • converterInfoconversa-----


This video can help you solving your question :)
By: admin