FROM : http://www.javaworld.com/javaworld/jw-12-2001/jw-1207-java101.html?
Trash talk, Part 1
Java recycles its memory through garbage collection
SummaryBy Jeff Friesen
One feature that distinguishes Java from other computer languages is its garbage collection abilities. In this article, Jeff Friesen introduces you to garbage collection and shows how Java's optional support for it affects your programs. While studying garbage collection, you will also learn about reachability, finalization, and resurrection.For answers to last month's homework, for this month's homework, and for additional material related to this article, visit the associated study guide. (4,400 words; December 7, 2001)
Printer-friendly version | Mail this to a friend
Advertisement | |
|
ake out the trash! When it's applied to computer languages, that command conjures up a different meaning than the one you're used to. In Java, trash, or garbage, is heap memory that a program allocates for objects but no longer references; such memory serves no useful purpose. Just as real-world garbage clogs a trash bin, as Java's garbage piles up, it reduces the total amount of heap memory. If the JVM does not remove that garbage, the JVM eventually runs out of heap memory and can't fulfill future program requests to allocate memory for new objects. To prevent that from happening, the JVM takes out the trash through its use of garbage collection.
In this article, I introduce you to garbage collection, a term computer developers commonly use to refer to memory recycling -- that is, the reuse of heap memory. After learning important details about garbage collection and its various algorithms, you'll learn the practical side of garbage collection from Java's perspective: how to ask the JVM to run the garbage collector, how to finalize objects, and how to resurrect finalized objects (and why that is a no-no!). We start exploring garbage collection by defining that term.
Read the whole series on garbage collection:
- Part 1. Java recycles its memory through garbage collection
- Part 2. The Reference Objects API allows programs to interact with the garbage collector
Note |
---|
Java's garbage collection activity is JVM-specific. As a result, the output from various programs that appear in this article will not necessarily match your output. Keep that in mind when you start reading the section entitled "Run Java's Garbage Collector." |
What is garbage collection?
From a source code perspective, you use the keyword new
to create an object. After you compile that source code into a classfile, the JVM eventually encounters an equivalent byte code instruction to create that object and initialize the object's instance fields to default values. If the object is a nonarray object, such as a single String
object, the JVM executes a new
byte code instruction to allocate memory for that object in the JVM's object heap, a pool of JVM memory that stores objects. However, if the object is an array object, the JVM executes one of the newarray
, anewarray
, or multianewarray
byte code instructions to perform the same tasks. In any case, the JVM reserves memory for the new object in its object heap. As long as that object exists, the JVM does not give that memory to some other object.
Each of the aforementioned byte code instructions returns a reference to the just-allocated memory chunk. That reference might be a C++-style pointer or some arbitrary value identifying that memory. What constitutes the reference depends on the JVM implementation; you do not need to know about it for the purposes of this discussion.
Typically, you assign the just-returned reference to some kind of reference variable whose type is either the same as or similar to the type of the just-created object. Alternatively, you might create a temporary object (making it temporary by not assigning its reference to any reference variable) to call one of that object's methods. For example, you might execute the following code fragment to print a circle's area by first creating a System.out.println ("Area = " + new Circle (10.0, 10.0, 25.0).area ());Circle
object with (10.0, 10.0) as the center and 25.0 as the radius, and then calling Circle
's area()
method via the newly returned reference:
The code fragment creates a Circle
object, calls its constructor to initialize that object to a specific center and radius, returns a Circle
reference, and uses that reference to call Circle
's area()
method, whose return value subsequently prints. After area()
returns, the Circle
's reference disappears from the program. That is why Circle
is known as a temporary object; without the reference, you can no longer call that object's instance methods.
What happens to an object when you lose its reference? In a language like C++, you have just tied up heap memory. Without the object's reference, that memory remains occupied until the program exits. In Java, however, the reference becomes eligible for garbage collection -- the process by which some executable, such as the JVM, automatically frees an object's memory when a single reference to that memory no longer exists.
When a Java program runs, a portion of most JVMs known as the garbage collector runs as a background thread to perform garbage collection. Because that thread runs occasionally at nondeterministic times, you do not know when it will run. (I will cover threads in a future article.)
To carry out garbage collection, the garbage collector thread performs at least the first of the following two main tasks:
- It frees an object's heap memory for later use by a subsequently created object. After all, heap memory is not infinite, and a moment comes when the JVM either needs to free object memory or shut down because all available heap memory has run out.
- It defragments the heap. As the JVM creates objects and its garbage collector frees the memory of unreferenced objects, the heap fragments. Free memory holes appear among blocks of memory assigned to objects. When the JVM attempts to create a new object, enough free memory, from the sum total of all holes, might be available to accommodate the object. However, there might not be a free memory hole large enough to hold the object's instance fields. Defragmentation moves all occupied objects' memory to one end of the heap. That memory serves as one large hole that the JVM can use to allocate memory for new objects.
Note |
---|
The Java Language Specification (JLS), which is the official word on the Java language, does not state that a JVM implementation must support a garbage collector. For example, a JVM implementation on a smart card -- a plastic card with an embedded processor -- might require all Java programs to fit within the confines of that card's memory. As a result, the smart card JVM would not need a garbage collector. However, most JVMs need garbage collectors. |
Page 1 Trash talk, Part 1
Page 2 Garbage collection algorithms
Page 3 Run Java's garbage collector
Printer-friendly version | Mail this to a friend
- Resources
- "Trash Talk," Jeff Friesen (JavaWorld)
- Download this article's source code and resource files:
http://www.javaworld.com/javaworld/jw-12-2001/java101/jw-1207-java101.zip
- For a glossary specific to this article, homework, tips, and more, see the Java 101 study guide that accompanies this article:
http://www.javaworld.com/javaworld/jw-12-2001/jw-1207-java101guide.html
- The Java Language Specification, Second Edition, James Gosling, Bill Joy, Guy Steele, and Gilad Bracha (Sun Microsystems, 2000):
http://www.javasoft.com/docs/books/jls/second_edition/html/j.title.doc.html
- The Java Tutorial, Mary Campione, Kathy Walrath, Alison Huml (Addison-Wesley, 2000; ISBN: 0201703939):
http://www.javasoft.com/tutorial/
- Sun's official Java language definition:
http://java.sun.com/docs/overviews/java/java-overview-1.html
- To experiment with Sun's HotSpot JVM generational collector, check out this issue of "Tech Tips," Stuart Holloway (Java Developer Connection, December 2000):
http://developer.java.sun.com/developer/TechTips/2000/tt1222.html
- To learn about tuning garbage collection, check out "Tuning Garbage Collection with the 1.3.1 Java Virtual Machine" (Sun Microsystems, 1999):
http://java.sun.com/docs/hotspot/gc/index.html
- To learn about the Train algorithm, visit "Incremental Mature Garbage Collection Using the Train Algorithm," Jacob Seligmann and Steffen Grarup:
http://www.daimi.aau.dk/~beta/Papers/Train/train.html
- To learn how to design classes for proper object cleanup, read "Object Finalization and Cleanup," Bill Venners (JavaWorld, June 1998):
http://www.javaworld.com/javaworld/jw-06-1998/jw-06-techniques.html
- Review Jeff's previous column, "Class and Object Initialization" (JavaWorld, November 2001):
http://www.javaworld.com/javaworld/jw-11-2001/jw-1102-java101.html
- Check out past Java 101 articles:
http://www.javaworld.com/javaworld/topicalindex/jw-ti-java101.html
- For additional articles on Core Java concepts, browse our Topical Index:
http://www.javaworld.com/channel_content/jw-core-index.shtml
- To read more about the Java Virtual Machine, search our Topical Index:
http://www.javaworld.com/channel_content/jw-jvm-index.shtml
- Need some Java help? Visit our Java Beginner discussion:
http://forums.devworld.com/webx?50@@.ee6b804
- Java experts answer your toughest Java questions in JavaWorld's Java Q&A column:
http://www.javaworld.com/javaworld/javaqa/javaqa-index.html
- For Tips 'N Tricks see:
http://www.javaworld.com/javaworld/javatips/jw-javatips.index.html
- Sign up for the JavaWorld This Week free Core Java newsletter:
http://www.idg.net/jw-subscribe
- You'll find a wealth of IT-related articles from our sister publications at IDG.net
'java core' 카테고리의 다른 글
Threads from aritma (0) | 2005.02.12 |
---|---|
Reference object model from java world (0) | 2005.01.28 |
자바 코드 컨벤션 (0) | 2005.01.24 |
J2ME쪽 JSR모음 (0) | 2005.01.24 |
Java 코딩 지침 (0) | 2005.01.24 |