Four types of references in Java

Source: Internet
Author: User

Four types of references in Java

Today, look at the code, there is a class java.lang.ref.SoftReference the younger brother to God, imagine, touch Java has been 3 years, wow, even lang package below the class are not understand, how to mix. Later on-line search information, feel a lot of harvest, is now recorded as follows.

strong, soft, weak, and virtual references to objects

In previous versions of JDK 1.2, if an object was not referenced by any variable, the program could no longer use the object. That is, only the object is in the accessible (reachable) state before the program can use it. Starting with JDK version 1.2, the reference to the object is divided into 4 levels, giving the program more flexibility in controlling the object's life cycle. These 4 levels are high to low in order: Strong references, soft references, weak references, and virtual references.

  

Strong references (strongreference)

  Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it. When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.

PS: Strong references are actually the meaning of our usual a = new A ().

Soft references (SoftReference)

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;  PublicImageData (String path) { This. Path =path; Dataref=Newsoftreference<byte[]> (New byte[0]); }    Private byte[] Readimage () {return New byte[1024 * 1024];//The operation to read a file is omitted    }     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 (WeakReference)

weaker than soft references in strength, by class WeakReference to say. 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.

Ghost Citation (Phantomreference)

Before introducing ghost references, 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. Ghost references (phantom Reference) can solve this problem. You must specify a reference queue when creating a ghost reference phantomreference. When an object's Finalize method has been called, the Ghost reference to the object is added to the queue. By checking the contents of the queue, you know whether an object is ready to be recycled.

Ghost references and their queues are rarely used, and are used primarily 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 the garbage collector to run             Try{queue.remove ();//the method blocks until the queue is not emptyRef.clear ();//Ghost references are not automatically emptied, to be run manuallyref =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. By referencing the queue's Poll/remove method, you can get the referenced objects in the queue in a non-blocking and blocking manner, respectively.

  

Four types of references in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.