1

I was trying to save one of the class object to a File using ObjectOutputStream. When My object grows with the size I get the below error otherwise it is all good.

Exception in thread "Thread-2" java.lang.OutOfMemoryError: Java heap space at java.io.ObjectOutputStream$HandleTable.growEntries(ObjectOutputStream.java:2308)

My code looks like this:

 try { FileOutputStream fout = new FileOutputStream("D:\\out.dat"); ObjectOutputStream os = new ObjectOutputStream(fout); os.writeObject(this.obj); // Writing object to a File os.close(); fout.close(); os=null; fout=null; } catch (Exception e) { e.printStackTrace(); } 

Please suggest me how can I resolve this? Any alternate approach to achieve the same?

2
  • What is this.obj that you want to write it?! Commented Jul 1, 2012 at 8:42
  • @nobeh obj is an object of the class that I'm using in the program. Commented Jul 1, 2012 at 8:48

2 Answers 2

3

Start your program with the -Xms1024M -Xmx1024M options. You don't usually get that error unless that object is really really big and/or you have a computer with a small RAM amount.

Sign up to request clarification or add additional context in comments.

2 Comments

My computer has 4GB RAM. other than increasing the JVM size no other option left to handle memory leaks. any memory optimization techniques can solve such problems? please comment your opinion.
@Vasant You can use a memory profiler to find out what your application is using in terms of cpu and memory. Once you have identified where in your application is using most cpu/memory then you can optimize it. Without this analysis all you can do is increase your memory.
3

I faced a similar problem sometime ago and I had the two following options to resolve this kind of problem:

  1. Increase JVM memory by tweaking the -Xms and -Xmx parameters
  2. If the object is really big then you should probably think of splitting it into smaller chunks that you can reassemble at read time

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.