• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why this program always gets an out-of-memory error  RSS feed

 
Charles Willisoms
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been recently researching how to make my java programs more efficient, and in the process I have written a small test program to give me some test timings, yet every time I run it, it eventually crashes after just a few seconds. (even though no new objects are created after the initialization part.) Can someone please help give me more insight on why this program always gets out-of-memory error, and if the code could be improved to avoid it. Does this have something to do with the Vector class in particular ??
Thanks,
Charles.

code follows :


(edited by Cindy to format code using [ code] and [ /code] tags without the spaces)
[ August 28, 2003: Message edited by: Cindy Glass ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Charles,
Welcome to JavaRanch!
Every item added to a Vector (or any Collection) consumes at least of small amount of space for the reference to the added object. In Vector's case, this is just one object reference (which typically consumes 4 bytes of real RAM.)
In your program, you create num_records objects, then insert innerLoop * outerLoop references to them into the Vector; for outerLoop = 100, innerLoop = 200000, this is 4 * 100 * 200000 = 80 megabytes of storage right there; I"m actually surprised the program as written works at all, because the default heap size is 64MB. I'm pretty sure your comments as to which values work and don't work are misleading. Anyway, there's not really any way to write a program that holds 20,000,000 references to objects in a Vector, List, or array using the default heap size; you can grow the heap using the -Xmx switch to the Java runtime.
Note that calling Runtime.gc() is just a suggestion to the JVM that it try to reclaim memory and, even if this suggestion were taken very seriously, only unreferenced memory can be reclaimed. You yourself state that after initialization, this app doesn't create additional objects, so I'm not really sure what objects you're trying to reclaim. Finally, note that before throwing an OutOfMemoryError, the JVM will do everything it possibly can to reclaim memory and retry, so calling Runtime.gc() is never actually necessary.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!