Java reference types
?? If an In-memory object does not have any references, it means that the object is no longer being used and can be a candidate for garbage Collection. however, since the runtime of the garbage collector is uncertain, the actual collection time of objects that can be garbage collected is Indeterminate. For an object, it persists in memory as long as there is a reference. If such objects become more and more, exceeding the total amount of memory in the jvm, the JVM throws a OutOfMemory Error. While the specific operation of garbage collection is controlled by the jvm, developers can still interact with the garbage collector to a certain extent, with the aim of helping the garbage collector manage the memory of the application in a better way. This interaction is the JAVA.LANG.REF package introduced with JDK 1.2, which is the structure hierarchy of the ref package in JDK1.7.
Reference is an abstract class, and softreference,weakreference,phantomreference and finalreference are the concrete classes that inherit it.
Strong references
?? In a generic Java program, the most visible is a strong reference (strong Reference). As Date date = new Date (), date is a strong reference to an Object. A strong reference to an object can be passed around in a Program. In many cases, multiple references are directed at the same object. The presence of a strong reference limits the time that an object survives in Memory. If object A contains a strong reference to object b, then in general, the lifetime of object B will not be shorter than Object A. If object A does not explicitly set the reference to object B to null, only if object A is garbage collected, and object B no longer has a reference to it, the opportunity to be garbage collected may be obtained.
In addition to strong references, the JAVA.LANG.REF package provides a different way to refer to an Object. The Jvm's garbage collector has different ways of handling different types of references.
Finalreference and Finzlizer
Finalreference as a java.lang.ref in a public access to the class, and what kind of role? As his subclass, what role does Finalizer play in the garbage collection mechanism?
In fact, Finalreference represents a strong reference in Java, such as this code:
Bean bean = new Bean();
During the implementation of the virtual machine, the Finalreference class is actually used to refer to it. Finalizer, In addition to being an implementation class, implements a Finalizerthread in the virtual machine so that the virtual machine can implement memory cleanup after all strong references are Lifted.
Soft references
?? Soft references (soft Reference) are weaker than strong references in strength and are represented by class Softreference. Its role is to tell the garbage collector which objects in the program are less important and can be temporarily reclaimed when the memory is low . When there is not enough memory in the jvm, the garbage collector releases objects that are only pointed to by soft references. If all of these objects are released, the memory is not enough to throw a outofmemory Error. Soft references are ideal for creating caches. When the system is running out of memory, the contents of the cache can be Freed. Consider an image editor program, for Example. The program will read the entire contents of the image file into memory for easy processing. Users can also open multiple files at the same time. When too many files are open at the same time, it can cause insufficient memory. If a soft reference is used to point to the contents of the image file, the garbage collector can reclaim the memory when Necessary.
public classImageData {PrivateString path;Privatesoftreference<byte[]> dataref; public ImageData(String Path) { this. Path = path; Dataref =Newsoftreference<byte[]> (New byte[0]); }Private byte[]Readimage() {return New byte[1024x768*1024x768];//omitted The operation of reading the file} public byte[]GetData() {byte[] DataArray = dataref.Get();if(dataarray = =NULL|| Dataarray.length = =0) {dataarray = Readimage (); Dataref =Newsoftreference<byte[]> (dataarray); }returndataarray; } }
?? When running the above program, you can use THE-XMX parameter to limit the memory available to the JVM. Because the object that the soft reference points to may be reclaimed, it is always checked to see if the object is still alive when it is used to get the object that the soft reference is actually pointing to by the get Method.
Weak references
?? Weak references (weak Reference) are weaker than soft references in strength and are represented by class Weakreference. It does this by referencing an object, but does not prevent the object from being recycled . If a strong reference is used, the referenced object cannot be reclaimed as long as the reference Exists. Weak references do not have this Problem. When the garbage collector runs, the object is recycled if all references to an object are weak references. The function of weak references is to solve the coupling relationship between objects brought by strong references in the time of Survival.
?? The most common use of weak references is in a collection class, especially in a hash table. The interface of a hash table allows any Java object to be used as a key. When a key-value pair is placed into a hash table, the Hashtable object itself has a reference to those keys and value Objects. If such a reference is a strong reference, the hash table object itself will not be recycled as long as it is Alive. If a long-lived hash table contains many Key-value pairs, it can eventually consume all of the memory in the JVM.
The solution to this situation is to use weak references to refer to these objects so that key and value objects in the hash table can be garbage collected. Weakhashmap is available in Java to meet this common need.
Virtual reference
?? Before you introduce a virtual reference, you should first describe the object termination mechanism (finalization) provided by Java. There is a Finalize method in the object class, which is designed to perform some cleanup work before an object is actually recycled. because Java does not provide a mechanism similar to that of C + + destructors, It is implemented by the finalize Method. But the problem is that the garbage Collector's run time is not fixed, so the actual running time of these cleanup work is Unpredictable. Virtual references (phantom Reference) can solve this problem. You must specify a reference queue when creating a virtual reference phantomreference. When an Object's Finalize method has been called, the Object's virtual reference is added to the Queue. By checking the contents of the queue, you know whether an object is ready to be recycled.
Virtual references and their queues are not used much, and are mainly used to achieve more granular memory usage control, which is significant for mobile Devices. The program can then request memory to create a new object after the object is determined to be recycled. In this way, the memory consumed by the program is kept to a relatively low number. For example, The following code gives a sample implementation of a Buffer.
public classPhantombuffer {Private byte[] data =New byte[0];Privatereferencequeue<byte[]> queue =Newreferencequeue<byte[]> ();Privatephantomreference<byte[]>ref=Newphantomreference<byte[]> (data, queue); public byte[]Get(intSize) {if(size <=0) {Throw NewIllegalArgumentException ("wrong Buffer size"); }if(data.length < Size) {data =NULL; System.GC ();//force Run Garbage collector Try{queue.remove ();//this method blocks until the queue is not empty ref. Clear ();//ghost references are not automatically emptied, to be run manually ref=NULL; data =New byte[size];ref=Newphantomreference<byte[]> (data, queue); }Catch(interruptedexception E) {e.printstacktrace (); } }returnData }}
?? In the preceding code, each time a new buffer is requested, it is first ensured that the byte array of the previous buffer has been successfully reclaimed. The Remove method of the reference queue is blocked until a new ghost reference is added to the Queue. however, It is important to note that this practice can cause the garbage collector to run too many times, which can cause the program to be too low in Throughput.
Reference queue
?? In some cases, the program will need to be notified when an Object's accessibility has Changed. For example, a strong reference to an object no longer exists, leaving only soft or weak references. But there is also a need to do some processing on the reference itself. A typical scenario is in a hash table. The reference object is the key object in the weakhashmap, and when the actual object it references is garbage collected, it is necessary to remove the key value pair from the hash table. With the reference queue (referencequeue), you can easily get these weakly referenced objects and remove them from the Table. References to actual objects are automatically emptied when soft references and weak reference objects are added to the Queue. Reference objects in the queue can be obtained in a non-blocking and blocking manner, respectively, by referencing the Poll/remove method of the Queue.
Resources
- In-depth discussion of Java.lang.ref PACKAGE-IBM
- In-depth discussion of Java.lang.ref Bag-blog Park
Java Virtual machine (vii)--understanding four types of reference