Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String, StringBuffer & OutOfMemoryError

 
Denis Denis
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have the code which read big UTF strings



In some cases this code throws OutOfMemoryError.
As I understand, it happens because StringBuffer cannot allocate enough memory space.
When in JVM I pass the parameter -Xmx256M, then I don't have this problems.

This kind of code doesn't make the same problem


As far as I know, String always reallocate memory when I work with it.
And this influence on execution time. I don't want to set -Xmx to JVM.
Where is the dog buried and how to resolve this question by another road?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where does that magic 21845 in the first version come from? It looks like the code is assuming that's the length of each string. But are all the strings the same length? If not, is 21845 the maximum or the typical length?

I would guess that all the strings are not the same length, and many are a lot shorter. In that case, the += version does better, because the StringBuffer version tries to allocate an unnecessarily big buffer. However, the += version is inefficient, as lots of unnecessary objects get created.

I think the best approach would be to use the StringBuffer version, but with a much smaller initial size. StringBuffer will resize itself as necessary.
 
Denis Denis
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Peter Chase. All string have the same size excepts the last.
We have assistant class for sending big UTF String and for receive them.
This class splits big string to blocks, then write blocks amount, and then write parted strings.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic