Java Reference
In-Depth Information
This statement creates two separate elements in memory: the reference e and
the Employee object. The reference e is not an object. The object itself does not
have a variable name, and the only way you can access and use the object is to
use a reference to the object.
Garbage Collection
In the previous section, I showed you how the new keyword is used to instan-
tiate objects. However, I have not discussed how to delete an object after you
are finished with it so the memory that the object is consuming can be freed.
In other OOP languages such as C++, memory has to be explicitly freed by
the programmer. In fact, C++ has a delete keyword that needs to be used to
free the memory of an object. If you forget to delete an object in C++ and you
lose any references to it, the memory can never be freed and you have created
what is referred to as a memory leak , which can wreak havoc on your programs,
especially programs that use large amounts of memory or run for long periods.
In Java, there is no keyword or operator that you can use to remove an object
from memory. Java was designed to avoid the problems of memory leaks that
arise in other languages. A JVM has a low-level thread known as the garbage
collector that is constantly running in the background, looking for objects in
your Java program that are no longer being used and freeing their memory.
The concept of automatic garbage collection makes programmers both
excited and nervous. Garbage collection is appealing because programmers do
not have to spend hours upon hours worrying about and/or trying to fix
memory leaks. Programmers get nervous, however, because they lose the con-
trol of being able to free memory at any point in a program because memory
will be freed in a Java program only when the garbage collector concludes that
the memory is no longer being used.
Classroom Q & A
Q: How does the garbage collector know when to remove an object
from memory?
A: Good question. It is important to understand the answer because
there are times when you want the garbage collector to free up
memory. An object is marked for garbage collection when it is no
longer reachable in your program.
Q: Does reachable mean when there are no more references to the
object?
A: No, but that is a common misunderstanding of garbage collection.
You might think that the garbage collector keeps count of how
Search WWH ::




Custom Search