Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 13 ■ GARBAGE COLLECTION

have gotten into a situation where garbage collection wouldn't work correctly, as I'd still be hanging
onto the Target objects.


■ Note Using a garbage collection hint will not prevent your program from running out of memory if it is about to


run out anyway. That's yet another reason to not use garbage collection hints. As a rule, they don't help.


Blocking Garbage Collection


Sometimes, you need an object to exist for as long as your program runs. To make sure it continues to
exist, you need to ensure that a reference to that object always exists. Java offers a couple of handy ways
to ensure a reference always exists: singletons and reference lists.
A singleton is a class that can never have more than one instance. Java developers have a number of
techniques for creating a singleton, but Listing 13-5 shows one common way to do it.


Listing 13-5. Making a Singleton


public class Singleton {


private static Singleton instance = new Singleton();


private Singleton() {
// initialization stuff goes here
}


public synchronized static Singleton instance() {
return instance;
}
}


Because there's always a static instance of the class held within the class itself, there's always a
reference to this kind of singleton. We make the instance method synchronized so that, if two objects
call the method at the same time, they take turns. Otherwise, they might get the object in the wrong state
(in cases where some other method updates the data in the singleton class). As a rule, synchronize any
method that returns a static object (not including constants).
Of course, if you need more than one instance of a class, that's not going to work. In those cases, you
can use a reference list. Consider the program class shown in Listing 13-6.


Listing 13-6. Program Class with a Reference List


package com.bryantcs.examples.referenceList;


import java.util.ArrayList;


public class ReferenceProgram {


// This list lasts as long as the program runs

Free download pdf