File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Performance
Bookmark "Memory management  - Best practices?" Watch "Memory management  - Best practices?" New topic

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.

Peter Haggar
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
Ranch Hand

Joined: Oct 26, 2000
Posts: 96
The online chapter of my book gives techniques to reduce memory consumption. At
--Jack Shirazi
I agree. Here's the link:
subject: Memory management - Best practices?
jQuery in Action, 3rd edition