This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Performance and the fly likes Memory management  - Best practices? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Memory management  - Best practices?" Watch "Memory management  - Best practices?" New topic
Author

Memory management - Best practices?

Alok Pota
Ranch Hand

Joined: Mar 07, 2001
Posts: 185
I guess managing the Java heap goes under Performance (Should this forum be called Optimization instead?) anyways..
Could anyone list coding techniques that programmers should use and avoid when it comes to managing the Java heap. More specifically I want to know the coding techniques to avoid that would eventually lead to an OutofMemoryError.

Alok
Peter Haggar
author
Ranch Hand

Joined: Jan 03, 2001
Posts: 106
A couple off the top of my head are:
- Make sure you always clean up non-memory resources. Things like file and socket handles. These are not cleared by the GC. All the GC handles in object memory.
- Don't clean up these resources in a finalize() method. They are not guaranteed to get called. A good place to code these is in finally blocks or somewhere where you know they will get called and release.
- Don't hang on to references to objects that you don't need. Sometimes this happens when a class is loaded that holds a reference to a large object, or many objects. Consider the case where, at some point, you need this class, but not everything it references. Since it is referencing these objects that you don't need it is wasting memory. You can specifically null these references in hopes that the GC will clean them up on a future run.
- You can also use command line options to increase the size of the heap that the VM uses.
Again, just a quick list, I'm sure others have some ideas too.
Peter Haggar
------------------
Senior Software Engineer, IBM
author of: Practical Java


Senior Software Engineer, IBM
author of: Practical Java
Jack Shirazi
Author
Ranch Hand

Joined: Oct 26, 2000
Posts: 96
The online chapter of my book gives techniques to reduce memory consumption. At http://www.oreilly.com/catalog/javapt/chapter/ch04.html
--Jack Shirazi http://www.JavaPerformanceTuning.com/
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Memory management - Best practices?