jnd
jnd

Reputation: 754

Reduce memory usage of ToStringBuilder (apache commons)?

I have a program which writes and then zips a large number of SQL statements into a file. However sometimes a user can select a large number of items to generate SQL statements on. For example, the SQL zip file might contain 4 files each 1+ million characters long as a result.

At present the SQL generation depends on the function:

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}

However this causes a huge spike in memory usage and results in the program crashing from a "java.lang.OutOfMemoryError: Java heap space” error. I have tried increasing the heap size but the program is still slow and still occasionally crashes.

Is there a way to reduce the memory consumption of the above method? It needs to be the whole object being output as the string (not just its name).Below is the graph of the application booting up, idle for a little while and then attempting to run before crashing. enter image description here

And here is what is using the memory: enter image description here

Upvotes: 4

Views: 1192

Answers (1)

Grégoire C
Grégoire C

Reputation: 1381

I had the same error ("java.lang.OutOfMemoryError: Java heap space") with:

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}

inside an abstract super class.

After I read Apache Commons Lang3 documentation, I solved the problem by using the function that doesn't use reflection and is said to be faster:

@Override
public String toString() {
    return new ToStringBuilder(this).append("id",id).toString();
}

where id is obviously a field in my superclass that I want to output.

This solves the problem of the heap overflow, and my application runs much faster now.

The only drawback is that toString output is now much simpler, but anyway this is used only for debugging so it's not a big deal.

Upvotes: 2

Related Questions