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, which is a package that implements strong, soft, weak, and virtual references in Java, as follows:


Phantomreference

Virtual reference: If an object holds a virtual reference, it can 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 activity of objects being garbage collected, and virtual references have a different place from weak and soft references where virtual references must be used in conjunction with reference queues. When the garbage collector prepares to reclaim an object, if it finds that it 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 know if the object is going to be recycled by judging whether a virtual reference has been added to the reference queue, so that we can do something before the object is recycled.

Reference

Reference base class: This is an abstract class that encapsulates related operations on references, such as removing references, comparing, getting referenced objects, and judging whether 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 there is not enough memory space, the garbage collector reclaims the memory object that the reference refers to. Soft references enable 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 reclaimed whether or not the memory is sufficient, but because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that hold only weak references, and weak references can 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 picture, the code is as follows:

Package soft reference; Import java.lang.ref.reference;/** * Encapsulates the base class of referenced objects * @author codeingsnail * * @param <T> */public abstract C Lass 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;} /** * Empties 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 example above, we define a referenced abstract class, and give the subclass two callback methods to create the picture object and the required soft reference (or a weak reference) to get an instance of the object in the Get () method. In fact, the above example is a generic method, and we can define the type of reference we need in getreference. If we are clear now that what we want is a soft reference, 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 use the following to analyze the Weakhashmap class under the Java.util package, open the JDK will find a long description of this class, let's take a look at the general 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, where key holds a weak reference to value. When the system reclaims the actual object corresponding to the key, Weakhashmap automatically deletes the corresponding Key-value pair for that key.
    /** * 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 WeakReference, and in the construction method you can see that the key is given directly to WeakReference and is associated with the 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 Weakhashmap that will be called in most common methods, which will remove all invalid references from the map in Referencequeue. Weakhashmap does not automatically release invalid references, only if the containing Expungestaleentries method is called. Let's take a look at the use of Weakhashmap in the following small example:
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 above example, there is no strong reference outside the first key, it is only printed once by the collector, the third key has an external strong reference, when we remove the external reference is also reclaimed by the garbage collector, the second key is referenced by the string constant pool, so there is always.


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.