41 - 03:52:42 CS61B Lecture 41 Monday May 4 2009 GARBAGE...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
05/04/09 03:52:42 1 41 CS61B: Lecture 41 Monday, May 4, 2009 GARBAGE COLLECTION ================== Objects take up space in memory. If your program creates lots of objects, throws them away, and creates more, you might eventually run out of memory. To reduce the chance that this will happen, Java has garbage collection. While the Java Virtual Machine (JVM) runs your program, it also spends little bits of time searching for objects that you’re no longer using, so it can reclaim their memory for use by other objects. You don’t have to know anything about garbage collection to be an effective Java programmer. But garbage collection is interesting because the JVM uses a lot of hidden data structures to manage memory. These data structures are hidden from your Java program--after all, the JVM, just like any other encapsulated module, should hide the details of how it is implemented. Here’s a peak at what’s going on under the hood. Roots and Reachability ---------------------- Garbage collection’s prime directive is to never sweep up an object your program might possibly use or inspect again. These objects are said to be _live_. The opposite of "live" is _garbage_--objects that your program cannot reference again. Java’s design makes it possible for the JVM to determine whether an object can ever be used again by your program or not. Garbage collection begins at the roots. A _root_ is any object reference your program can access directly, without going through another object. There are two kinds (that we know about). First, every local variable (including parameters) in every activation record on the program stack is a root if it is a reference. (Primitive types like ints are not roots; only references are.) Second, every class variable (aka "static" field) that is a reference is a root. Clearly, if an object is referenced by a root, it is live and should not be garbage collected. An object is also live if it is referenced by a field in another live object. Note that this definition is recursive. Another way to say it is that an object is live if it is _reachable_ from the roots. If you
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/21/2010 for the course CS 61B taught by Professor Canny during the Spring '01 term at Berkeley.

Page1 / 2

41 - 03:52:42 CS61B Lecture 41 Monday May 4 2009 GARBAGE...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online