Memory
Leaks in Java
The
fact that Java supports garbage collection dramatically reduces the incidence
of a class of bugs known as memory leaks. A memory leak occurs when
memory is allocated and never reclaimed. At first glance, it might seem that
garbage collection prevents all memory leaks because it reclaims all unused
objects. A memory leak can still occur in Java, however, if a valid (but unused)
reference to an unused object is left hanging around. For example, when a
method runs for a long time (or forever) , the local variables in that method
can retain object references much longer than they are actually required. The
following code illustrates:
Memory leaks can also occur when you use a hash table or
similar data structure to associate one object with another. Even when neither
object is required anymore, the association remains in the hash table,
preventing the objects from being reclaimed until the hash table itself is
reclaimed. If the hash table has a substantially longer lifetime than the
objects it holds, this can cause memory leaks.
No comments:
Post a Comment