Java Reference
In-Depth Information
There are lots of obviously bad things that you can do in a finalizer. One that almost everyone
points out is using the finalizer to place a reference to the object being finalized ( this ) into
some collection. Doing this resurrects the object, which means that the garbage collector will
no longer free up the space used by the object (or delete the object). But as the genie in Alad-
din said, bringing back the dead is a really bad idea. The genie was talking about people, but
the same is true with objects.
A less obvious bad thing can be shown if we extend our Player example to include the ability
to store Player objects in files. We do this by first making our PlayerImpl implement the
Serializable interface (about which much more will be said in Chapter 9 ) , add a private
static field that is the serialVersionUID (also discussed in that later chapter), and add a set of
fields to hold information that will be needed for reading from and writing to a file. Continu-
ing the tradition of using the filesystem as a database, we will store the player records in files
that are named using the String representation of the player's unique identifier, but we will
also add a String field which will hold the prefix that will let us identify the location of the
file (for example, the path to the directory that holds the file). We also add a field that will
hold the ObjectInputStream that we will use to read the player information to the file.
Next, we add a constructor that allows us to create a Player object with data initialized from a
file (if that file exists). This constructor takes a String (to identify the directory in which the
player's file is located) and the player ID. If the file is found and read, the fields of the newly
created Player object are initialized using the information from the file. If no file is found (or
if there is another problem with the file), the Player object is created with an unknown name
and the identifier passed in to the constructor.
Here is a first implementation of this scheme, complete with a finalizer (but eliding the code
that we have already seen):
public class PlayerImpl implements Player, Serializable {
private static final long serialVersionUID = 1;
private UUID id;
private String name;
private String filePrefix;
private Team team;
private Position pos = Position.Utility;
private boolean changed = false;
public PlayerImpl(UUID playerId, String prefix) {
id = playerId;
Search WWH ::

Custom Search