We help IT Professionals succeed at work.

Garbage Collection

Matlock asked
Medium Priority
Last Modified: 2012-08-13
Apart from pointing Strings and Images to null, when done with and calls to System.gc(),
Are there any tips anyone can give to improve how well the memory model performs for Java applications.
Watch Question

Nope, there isn't anything to be done beyond that. And I have had a large production program running for the last number of years, and there is no apparent need for anything more either.

If you are having a specific problem, perhaps that could be addressed.
Senior Engineer
I would say that there are a variety of programming techniques, design principles and JVM tweaks that impact Java memory management and performance. By far, the best advice related to reducing garbage collection can be summarized as "Don't create unnecessary objects." Since garbage collection is all about reclaiming memory used by unreferenced objects, reducing object construction will have a direct impact on garbage collection. This can appear in a variety of manifestations, some of which are actually good design/programming style but might have negative consequences depending on your implementation:

- heavy use of immutable objects
- using primitive wrapper classes instead of primitives
- String concatenation using the '+' operator
- throwing exceptions
- using Iterators and Enumerators for list traversal
- constructing StringBuffers and ArrayLists with default capacity
- duplicate or premature initialization

Here is a collection of links to articles which address these and similar topics:

Smart object-management saves the day

"Heap of trouble" with the wrong heap size

Tuning Garbage Collection with the 1.3.1 JVM

Java Garbage Collection and Setting to Null

Reference Objects and Garbage Collection

Performance Optimization for Java

Java Performance Tuning (Chapter 4 -- Object Creation)

Huge collection of performance tuning tips

Designing with Exceptions

Best regards,
Jim Cakalic
Here's a tip, don't call directly System.gc().

Let the garbage collector do his work when he feals like doing it.

Garbaging nulled objects is pretty fast, for example, garbaging 32m of nulled data took me 0.01 sec under jdk131 with HotSpot Server.


The bit about strings is something I can definitely look at following Imladris' comment though I'm going to open a new question specific to ONE remaining problem.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.