Java Reference
In-Depth Information
Memory leaks occur in Java programs not because you as the programmer forget to deallocate
some memory, but because you as a programmer forget and leave a reference to an object
hanging around in some other object when that reference is no longer needed. The way
garbage collection works is to find each object for which there is no longer a live reference
in the program. But a live reference is simply any reference in any other live object (or object
thought to be live) in the program. So forgetting to get rid of a reference can mean that an ob-
ject hangs around far longer than you ever intended. For many objects, this is not a problem.
Most objects are small, and most programs don't run for that long. But for large objects, or
long-running programs, such memory leaks can pile up. The result is the same kind of waxy-
yellow object buildup that you can get without garbage collection, along with lower perform-
ance and huge heaps.
Suppose, for example, that we want to keep track not only of the statistics for individual base-
ball players, but also for teams. To do this, we will need to aggregate a group of players into
a team. We will start by introducing a base interface of a Player that will contain the various
roles that we have already defined. Players will have names, but we will also assign identifi-
ers to them (since different players might have the same name, and we don't want to be con-
fused). Each player will also have a position and be part of a team. Such an interface might
look something like:
package org.oreilly.javaGoodParts.examples.statistics;
import java.util.UUID;
/**
*Basic interface for a player object.
*
*/
public interface Player {
enum Position {
Pitcher, Catcher, FirstBase, SecondBase,
ThirdBase, ShortStop, LeftField, CenterField,
RightField, DH, Utility
} /**
* Return the identifier for the player. This is just
* an <code>int</code>, generated when the player object is
* first created, used to distinguish between players
* that might have the same name.
*/
UUID getId();
Search WWH ::




Custom Search