Soft (weak) references in Java

Source: Internet
Author: User

First, strong, soft, weak, virtual reference in Java

In the JDK we can see that there is a java.lang.ref package. This package is a package that implements strong, soft, weak, and virtual references in Java, such as the following:


Phantomreference

Virtual reference: If an object holds a virtual reference, it may be reclaimed by the garbage collector at any time, just as it does not hold a reference.

Virtual references are primarily used to track the activities of objects that are garbage collected, and the virtual reference is different from a weak, soft reference where a virtual reference must be used in conjunction with a reference queue. When the garbage collector is ready to reclaim an object. Assuming that it also has a virtual reference, the virtual reference is added to the reference queue associated with it before the object memory is reclaimed.

The program can infer whether the object is going to be recycled by inferring that the reference queue has been added to the virtual reference, so that we can do something before the object is recycled.

Reference

Reference base class: This is an abstract class. Encapsulates a related operation on a reference. such as removing references, comparing them, getting reference objects, and inferring that the reference addresses are equal.

Referencequeue

Reference queue: The reference is added to the queue before the object is reclaimed by the garbage collector.

SoftReference

Soft reference: If the memory space is insufficient, the garbage collector reclaims the memory object that the reference refers to. Soft references enable fast, memory-sensitive caching, and soft references can be used in conjunction with reference queues.

WeakReference

Weak references: When the garbage collector discovers that an object has only a weak reference, the object is recycled regardless of whether the memory is sufficient or not. Because the garbage collector is a very low-priority thread, it is not necessarily very fast to find objects that hold only weak references. Weak references can also be used in conjunction with reference queues.

Examples of second soft (weak) references

Let's use the soft reference to read a picture, read the width and height of the image, the code is as follows:

package soft reference; Import java.lang.ref.reference;/** * Encapsulates the base class for referenced objects * @author codeingsnail * * @ Param <T> */public abstract class Referenceobject<t>{public reference<t> ref;protected abstract T getinstance ();p rotected abstract reference<t> getreference (T t);/* * Get reference objects and weak references */private T Getrefrenceandinstance () {T t = getinstance (); getreference (t); return T;} /** * Gets the referenced object * @return */public T get () {if (ref = = NULL) {return getrefrenceandinstance ();} T t = ref.get (); if (t = = null) {return getrefrenceandinstance ();} return t;} /** * Clears the object's reference. Reclaims the object */public void Recycle () {if (ref! = null) {ref.clear (); ref = NULL;}}} 
Import Java.lang.ref.reference;import java.lang.ref.softreference;import javax.swing.imageicon;/** * Reference Picture Resource class * @ Author Administrator * */public class Referencebitmap extends Referenceobject<imageicon>{string url;public Referencebitmap (String url) {this.url = URL;} @Overrideprotected reference<imageicon> getreference (ImageIcon imageicon) {return new softreference< Imageicon> (ImageIcon);} @Overrideprotected ImageIcon getinstance () {return new ImageIcon (URL);}}
Package soft reference; public class Client {private referencebitmap referencebitmap;public static void Main (string[] args) {Client cl ient = new Client (); client.referencebitmap = new Referencebitmap ("E:\\test.png"); System.out.println ("The height of the picture is:" + client.referenceBitmap.get (). Geticonheight ()); System.out.println ("The width of the picture is:" + client.referenceBitmap.get (). Geticonwidth ());}}
In the above example, we define a referenced abstract class, and give the subclass two callback methods to create a picture object and the required soft reference (also can be a weak reference), in the Get () method to get an instance of the object. In fact, the above example is a common method. We can define the type of reference we need in getreference. If we understand now that we want soft references, we can simplify the code as follows:

public class Client {softreference<imageicon> softrefrence;private referencebitmap referencebitmap;public static void Main (string[] args) {Client client = new Client (); client.referencebitmap = new Referencebitmap ("E:\\test.png" ); System.out.println ("The height of the picture is:" + client.referenceBitmap.get (). Geticonheight ()); System.out.println ("The width of the picture is:" + client.referenceBitmap.get (). Geticonwidth ());//simplified Method client.softrefrence = new Softreference<imageicon> (New ImageIcon ("E:\\test.png")); System.out.println ("The height of the picture is:" + client.softRefrence.get (). Geticonheight ()); System.out.println ("The width of the picture is:" + client.softRefrence.get (). Geticonwidth ());}}
Third, how to cooperate with the reference queue using the following to analyze the Weakhashmap class under the Java.util package, open the JDK will find a very long descriptive narrative of this class. Let's take a look at the approximate meaning.Hash table based implementation of the Map interface, with weak keys.An entry in a weakhashmap would automatically be removed when it key is no longer on ordinary use.More precisely, the presence of a mapping for a given key would not be prevent the key from being discarded by the garbage Collector, that's, made finalizable, finalized, and then reclaimed. When a key have been discarded its entry are effectively removed from the map, so this class behaves somewhat differentl Y from the other MAP implementations.The approximate meaning of this sentence is that the Weakhashmap hash table is based on the map interface. A weak reference to value is stored in key. After the system reclaims the actual object corresponding to the key. Weakhashmap will voluntarily delete the key corresponding to the key-value pair.
    /** * The entries in this hash table extend WeakReference, using its main ref * field as the key.  */private static Class Entry<k,v> extends Weakreference<object> implements map.entry<k,v> {V        Value        final int hash;        Entry<k,v> Next;         /** * Creates new entry. */Entry (Object key, V value, referencequeue<object> queue, int hash, entry<k,v& Gt            Next) {Super (key, queue);            This.value = value;            This.hash = hash;        This.next = Next;        } @SuppressWarnings ("Unchecked") public K GetKey () {return (K) weakhashmap.unmasknull (Get ());        } public V GetValue () {return value;            Public V SetValue (v newvalue) {v oldValue = value;            value = newvalue;        return oldValue; } public boolean equals (Object o) {if (! ( o InstaNceof map.entry)) return false; map.entry<?,? > E = (map.entry<?

,?>) O; K K1 = GetKey (); Object K2 = E.getkey (); if (k1 = = K2 | | (K1! = null && k1.equals (K2))) {V V1 = GetValue (); Object v2 = E.getvalue (); if (v1 = = V2 | | (V1! = null && v1.equals (v2))) return true; } return false; } public int hashcode () {k k = GetKey (); V v = getValue (); Return Objects.hashcode (k) ^ Objects.hashcode (v); } public String toString () {return GetKey () + "=" + GetValue (); } }

Weakhashmap.entry inherits from the WeakReference, and in the construction method can see that the key is given directly to WeakReference and is associated through Referencequeue.

    /** * expunges stale entries from the table. */private void expungestaleentries () {for (Object x; (x = Queue.poll ()) = null; {synchronized (queue) {@SuppressWarnings ("unchecked") entry<k,v> E                = (entry<k,v>) x;                int i = indexfor (E.hash, table.length);                Entry<k,v> prev = table[i];                entry<k,v> p = prev;                    while (P! = null) {entry<k,v> next = P.next;                        if (p = = e) {if (prev = = e) Table[i] = next;                        else Prev.next = next;                        Must not null out e.next; Stale entries may is in use by a hashiterator e.value = null;                        Help GC size--;                    Break } prev = P;                    p = Next; }            }        }    }
There is a private expungestaleentries method in the Weakhashmap. is called in most common-owned methods, and this method removes all invalid references from the map in the referencequeue. Weakhashmap does not voluntarily release the failed reference, but only if the included Expungestaleentries method is called. Here's a sample sample to look at the use of Weakhashmap:
public static void Main (string[] args) {weakhashmap<string, string> map = new weakhashmap<string, string> (); m Ap.put (New String ("1"), "1"), Map.put ("2", "2"); string s = new String ("3"), Map.put (S, "3"), int i = 0;while (map.size () > 0) {try {thread.sleep];} catch (Interruptede Xception e) {e.printstacktrace ();} System.out.println ("Map Size:" + map.size ()); System.out.println (Map.get ("1")); System.out.println (Map.get ("2")); System.out.println (Map.get ("3")); if (i = = 3) s = null; System.GC (); i++;}}
Output Result:
Map size:3123map size:2null23map size:2null23map size:2null23map size:1null2nullmap size:1null
In the example above. There is no strong reference outside the first key, it is only printed once and is recycled by the collector, and the third key has an external strong reference. When we remove an external reference, it is also reclaimed by the garbage collector. The second key is referenced by a string constant pool, so it always exists.


Soft (weak) 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.