This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes String, StringBuffer & OutOfMemoryError Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "String, StringBuffer & OutOfMemoryError" Watch "String, StringBuffer & OutOfMemoryError" New topic

String, StringBuffer & OutOfMemoryError

Denis Denis

Joined: Apr 03, 2007
Posts: 5
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

Joined: Oct 30, 2001
Posts: 1970
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.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Denis Denis

Joined: Apr 03, 2007
Posts: 5
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.
I agree. Here's the link:
subject: String, StringBuffer & OutOfMemoryError
It's not a secret anymore!