File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ERROR: java.lang.OutOfMemoryError: Java heap space

 
Vinith Kumar
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am facing OutOfMemory exception in Java, Kindly help me to resolve this issue, really appreciate your help

ERROR: java.lang.OutOfMemoryError: Java heap space

CODE:



Thanks in advance...

[Edit - added code tags - MB]

 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first thing that stands out in your code is that you are allocating a byte array with 50 million bytes in line 9. It looks like you read in a file in lines 12-27 into a byte array, resizing and copying the array to make it larger if the file is even bigger. If you read in a really large file (tens or hundreds of megabytes or bigger) then this can easily lead to an OutOfMemoryError.

To avoid this you could start the JVM with the -Xmx parameter to allow it to allocate more memory. For example: java -Xmx512M org.mypackage.MyProgram will allow it to allocate up to 512 MB RAM.

However, that only taking away the symptom. It would be better to rewrite that code so that it isn't necessary to read the data for the blob into a large buffer in memory. I don't know exactly how to do it right now but as far as I know, when you want to insert a blob in the database, you do not need to have the data in memory - you can pass it an InputStream (for example a FileInputStream) and the JDBC driver will read the data from there to insert it into the database.
 
Badal Chowdhary
Ranch Hand
Posts: 34
Eclipse IDE Java Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are tools to visualize the state of heap. The heap should be dumped to a .hprof file at the first occurrence of OutOfMemoryError. Eclipse Memory Analyzer can open .hprof file and you can then visualize the heap. See this post for more details:
http://badalchowdhary.wordpress.com/2011/11/09/java-heap-memory-analyzer/

Thanks,
Badal
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic