Java Reference
In-Depth Information
6.2
T rading C++ for Java
Running through the Elbow after Randy, I'm glad to be in my tiny kayak. I am
not expecting a problem making the S-turn, nor do I expect to hang up on the bot-
tom. The two-blade paddle will help me brace on either side for stability. I need
only make the initial critical turn, get into the flume, and brace. From that point
on the turbulent water will steer me down the flume as it has the three kayakers
before me. As I reach the initial turn, my front end hits turbulence—as I
expected—but then skips over the water that I'd counted on to turn my boat. Out
of control, I hit the same rocky outcropping as Randy. The mistakes are different,
but the result is the same.
When I decided to eschew C ++ and learn Java, I'd been frustrated with the
amount of time required to handle tedious matters unrelated to my business
problem. As a team leader, I'd spent hours tracking down dangling pointers,
memory leaks, and off-by-one errors. C ++ felt like a long, awkward canoe.
When I moved to Java, I felt invulnerable in my new “kayak.” I marveled
in condescending glee at the things that Java handled for free, while my C++
friends struggled with memory-management issues. Then, I encountered my
first Java memory leak, and I discovered that my tools and skills were not
adequate. I hadn't known that Java memory leaks could even exist, let alone
how to find them. It took me a week to solve my first Java memory leak. My
memory-management days weren't behind me, after all.
6.2.1
Circumstances that cause Java memory leaks
Though garbage collection in Java is sophisticated, certain patterns can still
cause memory leaks. An object's transition through states from allocated to
freed is known as its life cycle . From a garbage-collection standpoint, an object
goes from being unallocated, to allocated, to live, to unused, to garbage-col-
lected. A live object is one that is being actively used by a program. Java mem-
ory leaks tend to occur when a reachable object with a long life cycle has a
reference to an object with a shorter life cycle. In short, memory leaks are
objects that are reachable, but not live. Figure 6.2 shows two ways that gar-
bage collection can occur:
All references to an object by all reachable objects must be removed. In
figure 6.2, F has references from object C, which must be removed for
F to be collected.
All references to another object, needed for an object to be reachable,
must be removed. In figure 6.2, references from B and C to D will
Search WWH ::




Custom Search