Java Reference
In-Depth Information
Recall that Java implements a different strategy. Java applications request
objects, and the interpreter allocates the memory for the object. Because Java
handles allocation for the programmer and all variables are represented as
higher level objects, the Java programmer doesn't need to bother with pointer
arithmetic. In fact, pointer arithmetic was explicitly avoided in the Java design
to increase the stability and security of the language. Memory is not explicitly
freed. Instead, Java handles deallocation of memory through a process called
garbage collection.
6.1.2
Understanding garbage collection
Heaps are usually managed as a linked list or with a reference table pointing to
blocks of memory. An allocated block is marked in the table or taken out of
the chain. With allocation, a suitable block is found, subdivided, marked, and
returned to the requesting application. To prevent fragmenting, some mem-
ory managers periodically coalesce memory or combine contiguous blocks
into one big block. Automatic allocation of memory isn't difficult. The size of
the memory block and the block usage are known in advance. The memory
manager simply goes to the heap and walks through the free blocks until a
block of sufficient size is found.
Garbage collection is the act of periodically finding unused memory and
returning it to the heap. Doing it well is much more difficult than allocation.
The garbage collector cannot reliably guess the programmer's intent, so it
must use some other means to identify memory blocks to free. We'll discuss
two important garbage-detection techniques: reference counting and
unreachable nodes.
6.1.3
Reference counting
Early garbage collectors used a technique called reference counting . With this
algorithm, each object has a counter. When an object is allocated or used, the
associated counter is incremented. When the object is no longer referenced, it
is freed. The garbage collector can periodically sweep through all allocated
objects and free any objects with a reference counter of 0.
In figure 6.1, the circles represent allocated objects in the form of a
directed graph, or a group of interconnected objects. Connections between
objects are called edges . In our case, the edges are directed because an object
that explicitly references another provides direction for our arrows. Our
graph's objects are labeled with a name and reference count in parentheses.
The objects above the line are in use, and the objects below the line are no
longer in use.
Search WWH ::




Custom Search