Java Reference
In-Depth Information
public static ArrayList<Object> referenceList;
public static void main(String[] args) {
referenceList = new ArrayList<Object>();
}
}
As the comment within the class says, the referenceList object will have a reference for as long as the
program runs. So far, so good, but how do we add to it? The trick to that is to have any class we need to
keep around to add itself to the list, as shown in the next code listing:
Listing 13-7. Class that Adds Itself to a Reference List
package com.bryantcs.examples.referenceList;
public class ClassToList {
public ClassToList() {
ReferenceProgram.referenceList.add(this);
}
}
Since ReferenceProgram.referenceList is static, it is a class variable, which means there's only one
of them, regardless of the number of instances we may make of the ReferenceProgram class. (Of course,
in this very simple example, we wouldn't make more than one instance of the ReferenceProgram class
anyway.) As a result, we can add to that single list from anywhere within the program. Thus, we have a
handy mechanism for ensuring that a reference to any given class always exists and, consequently, that
any instance of this class will never be garbage collected.
While these techniques work, you should avoid overusing both the singleton pattern and the
reference list pattern. If you prevent the garbage collector from removing many objects, your program
performs that much more slowly.
A New Garbage Collector
As we saw earlier in the chapter, Java 7 includes a new garbage collector, called G1. G1 is a concurrent
garbage collector, meaning that it uses multiple processors (if available) at the same time. Also, as we
read earlier in the chapter, the G1 collector's “garbage first” algorithm offers better performance than
other collectors, regardless of the number of processors. For a computer with just one processor (or a
shared computer that makes only one processor available to the JVM), G1 should offer some
improvement over any other garbage collector (though the nature of the application may limit the
improvement). If G1 can get access to at least two processors, the improvement in performance should
be even better. Given that most modern computers have multiple processors and modern server-class
computers often have numerous processors, G1 may provide a sizable performance boost for some
applications. That's going to result in games that play more smoothly, web applications that return web
pages more quickly, and all the other good things that come with higher-performance applications.
Search WWH ::




Custom Search