Iv. Java references
|
Level |
When is garbage collection? |
Purpose |
Survival time |
|
strong |
never |
general state of the object |
stop when JVM stops running |
|
soft |
when the memory is insufficient |
simple object? Cache |
terminate when the memory is insufficient |
|
weak |
During garbage collection |
Object cache |
end after GC operation |
|
Illusion |
Unknown |
Unknown |
Unknown |
1. Strong reference:
Public static void main (string [] ARGs ){
Mydate date = new mydate ();
System. GC ();
}
Explanation: Even if garbage collection is explicitly calledDateIs a strong reference,DateNot recycled
2. Soft reference:
Public static void main (string [] ARGs ){
Softreference ref = new softreference (New mydate ());
Drainmemory ();//Let soft references work
}
Explanation: When the memory is insufficient, soft reference is terminated, equivalent:
Mydate date = new mydate ();
//-------------------ByJVMDecide to run-----------------
If (JVM.Insufficient memory()){
Date = NULL;
System. GC ();
}
//-------------------------------------------------------------
3. Weak references:
Public static void main (string [] ARGs ){
Weakreference ref = new weakreference (New mydate ());
System. GC ();//Make weak references work
}
Explanation: InJVMWhen garbage collection is running, the weak reference is terminated, which is equivalent:
Mydate date = new mydate ();
//------------------Garbage Collection------------------
Public void weaksystem. GC (){
Date = NULL;
System. GC ();
}
4. Hypothetical reference:
Public static void main (string [] ARGs ){
Referencequeue queue = new referencequeue ();
Phantomreference ref = new phantomreference (New mydate (), queue );
System. GC ();//Make hypothetical reference work
}
Explanation: the hypothetical reference is terminated after being instantiated. It is equivalent:
Mydate date = new mydate ();
Date = NULL;
//-------Termination point. after instantiationGCWhen the memory is insufficient--------
Http://hi.baidu.com/mynetbeans/blog/item/d72208fa8d63ac1ba9d31160.html