If you want to write a JavaProgramTo observe when an object will be cleared by the execution thread of the garbage collection, you must use a reference to remember this object so that you can observe it at any time, however, as a result, the number of references of this object cannot be zero and the object cannot be cleared.
Java. Lang. Ref. weakreference
However, with the weak reference, this can be solved. If you want to obtain the information of an object at any time, but do not want to affect the garbage collection of this object, you should use weak reference to remember this object, rather than general reference.
A obj = new ();
Weakreference wR = new weakreference (OBJ );
OBJ = NULL;
// Wait for a while and the OBJ object will be reclaimed
...
If (WR. Get () = NULL ){
System. Out. println ("OBJ has been cleared ");
} Else {
System. Out. println ("OBJ has not been cleared, and its information is" + obj. tostring ());
}
...
In this example, get () can be used to obtain the object referred to by this reference. If the outgoing value is null, it indicates that the object has been cleared.
This kind of technique is often used in the design of programs such as optimizer or debugger, because such programs need to obtain information about an object, but it cannot affect the garbage collection of this object.
Java. Lang. Ref. softreference
Although soft reference is similar to weak reference, it is used differently. Objects referenced by soft reference are not cleared even if there is no direct reference. It is cleared until the JVM memory is insufficient and no direct reference is available. softreference is used to design the object-cache. In this way, softreference not only caches objects, but also does not cause memory insufficiency errors (outofmemoryerror ). I think soft reference is also suitable for implementing pooling skills.
A obj = new ();
Softrefenrence sr = new softreference (OBJ );
Reference
If (SR! = NULL ){
OBJ = Sr. Get ();
} Else {
OBJ = new ();
Sr = new softreference (OBJ );
}