Java Reference
In-Depth Information
4.2.5 Releasing memory and garbage collector
In Java, one does not need to explicitly release memory of unused memory
structures such as arrays. The Java virtual machine (JVM) does it fully
automatically using the garbage collector . Once the JVM detects that elements
of an array cannot be accessed anymore because the reference of that array
has been released by, say, the function call stack, the garbage collector will
free that memory. This is a key difference with another popular programming
language: C++. The garbage collector checks at any time whether elements of
a given array can still be accessed by some variables holding a reference to that
array or not. If not, the garbage collector releases that global memory and will
perform some memory cleaning operations. Nevertheless, we can also explicitly
indicate to the JVM that we do not want the array anymore by setting the
reference of that array to null , meaning that we erase the array reference:
int [] array=new int[32];
array=null; // explicitly indicate to the JVM to release the array
4.3 The fundamental concept of array references
Whether the array is declared as a local variable or as a global (static/class)
variable, all its elements are stored in the program global memory. That is, even
if local array variables are declared, created and initialized within a function,
their elements may still be accessed by the calling function once the function
is completed. This provides an essential mechanism for voluntarily having side-
effect phenomena in functions that can therefore potentially change the (global)
program environment. An array variable array is dealt as a reference to that
array, a single machine word from which its indexed elements can be accessed.
The notion of reference for non-primitive types in Java is essential. It can
be quite delicate to grasp at first for novice programmers but nevertheless
is essential. The main advantages of handling array variables (whatever their
sizes) as references (a single machine word using four bytes 2 ) are as follows:
- References provide a mechanism for functions to access and modify elements
of arrays that are preserved when functions exit.
- When calling a function with array arguments, Java does not need to
allocate the full array on the function call stack , but rather pass a single
reference to that array. Therefore it is computationally and memory ecient.
2 That is equivalently 32 bits to reference a given memory location.
 
 
Search WWH ::




Custom Search