csua.org/u/7ng -> java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html
Appendix A The Truth About Garbage Collection Garbage collection (GC) is probably the most widely misunderstood feature of the Java platform. GC is typically advertised as removing all memory management responsibility from the application developer. On the other hand, some developers bend over backwards trying to please the collector, and often wind up doing much more work than is required. A solid understanding of the garbage collection model is essential to writing robust, high-performance software for the Java platform. This appendix provides an overview of the garbage collection mechanisms that will help you make intelligent choices about memory management issues. It also contains information to help you debug complex problems such as memory leaks. The cost of allocating and collecting memory can play a significant role in how your software performs. The overall memory requirements of your software can have a huge impact on the speed of your program when large RAM requirements force the OS to use virtual memory. This often occurs when memory is allocated, but not properly released. Although the JVM is responsible for freeing unused memory, you have to make it clear what is unused. To write successful, large-scale programs, you need to understand the basics of the GC mechanism. A2 The Guarantees of GC The specification for the Java platform makes very few promises about how garbage collection actually works. Here is what the Java Virtual Machine Specification (JVMS) has to say about memory management. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements.
Similarly, it might preclude useful optimizations and hurt the performance of the platform in the long term. Although there is no one place that contains a full definition of required garbage collector behavior, much of the GC model is implicitly specified through a number of sections in the Java Language Specification and JVMS While there are no guarantees about the exact process followed, all compliant virtual machines share the basic object lifecycle described in this chapter. A3 The Object Lifecycle In order to discuss garbage collection, it is first useful to examine the object lifecycle. An object typically goes through most of the following states between the time it is allocated and the time its resources are finally returned to the system for reuse.
The exact costs of these operations depend on the implementation of the JVM, as well as the implementation of the class being constructed. Once the object has been created, assuming it is assigned to some variable, it moves directly to the in use state. A32 In Use Objects that are held by at least one strong reference are considered to be in use. Java 2 introduces three other kinds of references: weak, soft and phantom.
Figure A-1 shows the structure of the objects inside the VM just before the makeCat method returns. At that moment, two strong references point to the Cat object.
When the makeCat method returns, the stack frame for that method and any temporary variables it declares are removed. This leaves the Cat object with just a single reference from the catList static variable (indirectly via the Vector). A33 Invisible An object is in the invisible state when there are no longer any strong references that are accessible to the program, even though there might still be references. Not all objects go through this state, and it has been a source of confusion for some developers.
Listing A-2 shows a code fragment that creates an invisible object. It might seem that the foo temporary reference variable would be pulled off the stack at this point and the associated object would become unreachable. After all, once the try block finishes, there is no syntax defined that would allow the program to access the object again. However, an efficient implementation of the JVM is unlikely to zero the reference when it goes out of scope. The object referenced by foo continues to be strongly referenced, at least until the run method returns. Because invisible objects can't be collected, this is a possible cause of memory leaks. If you run into this situation, you might have to explicitly null your references to enable garbage collection. A34 Unreachable An object enters an unreachable state when no more strong references to it exist. When an object is unreachable, it is a candidate for collection. Note the wording: Just because an object is a candidate for collection doesn't mean it will be immediately collected. The JVM is free to delay collection until there is an immediate need for the memory being consumed by the object. It's important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes * Temporary variables on the stack (of any thread) * Static variables (from any class) * Special references from JNI native code Circular strong references don't necessarily cause memory leaks.
Figure A-2 shows the reference graph for the objects before the buildDog method returns. Before the method returns, there are strong references from the temporary stack variables in the buildDog method pointing to both the Dog and the Tail.
Figure A-3 shows the graph for the objects after the buildDog method returns. At this point, the Dog and Tail both become unreachable from a root and are candidates for collection (although the VM might not actually collect these objects for an indefinite amount of time). A35 Collected An object is in the collected state when the garbage collector has recognized an object as unreachable and readies it for final processing as a precursor to deallocation. If the object has a finalize method, then it is marked for finalization. If it does not have a finalizer then it moves straight to the finalized state. If a class defines a finalizer, then any instance of that class must have the finalizer called prior to deallocation. This means that deallocation is delayed by the inclusion of a finalizer. A36 Finalized An object is in the finalized state if it is still unreachable after its finalize method, if any, has been run. Note that the VM implementation controls when the finalizer is run. The only thing that can be said for certain is that adding a finalizer will extend the lifetime of an object. This means that adding finalizers to objects that you intend to be short-lived is a bad idea. You are almost always better off doing your own cleanup instead of relying on a finalizer. Using a finalizer can also leave behind critical resources that won't be recovered for an indeterminate amount of time. If you are considering using a finalizer to ensure that important resources are freed in a timely manner, you might want to reconsider. One case where a finalize method delayed GC was discovered by the quality assurance (QA) team working on Swing. The QA team created a stress testing application that simulated user input by using a thread to send artificial events to the GUI. Running on one version of the toolkit, the application reported an OutOfMemoryError after just a few minutes of testing. The problem was finally traced back to the fact that the thread sending the events was running at a higher priority than the finalizer thread. The program ran out of memory because about 10,000 Graphics objects were held in the finalizer queue waiting for a chance to run their finalizers. It turned out that these Graphics objects were holding onto fairly substantial native resources. The problem was fixed by assuring that whenever Swing is done with a Graphics object, dispose is called to ensure that the native resources are freed as soon as possible. In addition to lengthening object lifetimes, finalize methods can increase object size. For example, some JVMs, such as the classic JVM implementation, add an extra hidden field to objects with finalize methods so th...
|