Topic |
Notes |
JVM's
garbage collection. |
- Java
manages memory for you.
|
- The
JVM will only perform garbage collection if it needs more
memory to continue executing. Helps efficiency.
|
- You
can make a call to garbage collection with System.gc(),
but this does not guarantee when it will happen.
|
- JVM
runs the object's finalize() method prior to garbage collection.
In other words, Java notifies the object.
|
- The
garbage collector does not claim objects in any certain
order. Helps efficiency.
|
- If
the JVM is halted at the conclusion of the program, it
could be that no garbage collection ever occurs.
|
|
Candidate
for Garbage Collection |
- Any
object is a candidate for garbage collection when your
program can no longer reference it (orphaned object).
|
- Local
variables are candidate for garbage collection when the
method returns (finished).
|
- Any
object is available for garbage collection after
it is set to "null". (ex: strX="Hello";
strX=null;)
|
- If
you reuse a reference object, the prior object is a candidate.
(ex: String strX ="Hello";
strX = "Hello2") or (ex: int [] MyArray
= {1,2,3}; MyArray = new int[3];)
|
|
Other
notes |
- finalize()
could be a good place to close files and other resources.
|
- Always
invoke the superclass's finalize() method if you override
finalize().
|
- gc()
(in Runtime & System) will allow you to directly run
the garbage collector.
|
- finalize()
signature:
protected void finalize() throws Throwable()
|
- To
use finalize() you must use a try-catch block or
rethrow the error object.
|
|