Java中的軟(弱)引用

來源:互聯網
上載者:User

標籤:read   輸出   類型   對象記憶體   推斷   另一個   when   基類   nts   

一、Java中的強、軟、弱、虛引用

在JDK中我們能夠看到有一個java.lang.ref的包。這個包中就是Java中實現強、軟、弱、虛引用的包,例如以下:


PhantomReference

虛引用:假設一個對象持有虛引用,就和沒有持有引用一樣,在不論什麼時候都可能被記憶體回收行程回收。

虛引用主要用來跟蹤對象被記憶體回收的活動,虛引用另一個和弱、軟引用不同的地方是虛引用必須和引用隊列聯合使用。當記憶體回收行程準備回收一個對象時。假設發現它還有虛引用,就會在回收對象記憶體之前,把這個虛引用加入到與之關聯的引用隊列中。

程式能夠通過推斷引用隊列中是否已經加入了虛引用,來知道對象是否將要被回收,這樣我們就能夠在對象被回收之前進行一些操作。

Reference

引用基類:這是一個抽象類別。封裝了關於引用的相關操作。如去除引用、比較、得到引用對象、推斷引用地址是否相等。

ReferenceQueue

引用隊列:在記憶體回收行程回收對象之前,會將該引用加入到該隊列。

SoftReference

軟引用:假設記憶體空間不夠用時,記憶體回收行程就會回收該引用所引用到的記憶體對象。使用軟引用能夠實現記憶體敏感的快速緩衝,軟引用能夠和引用隊列聯合使用。

WeakReference

弱引用:當記憶體回收行程發現某個對象僅僅有弱引用時不管是否記憶體夠用都會回收該對象,只是。因為記憶體回收行程是一個優先順序非常低的線程,因此不一定會非常快發現僅僅持有弱引用的對象。弱引用也能夠和引用隊列聯合使用。

二、一個軟(弱)引用的範例

以下我們來使用軟引用讀取一張圖片,讀出圖片的寬和高,代碼例如以下:

package 軟引用;import java.lang.ref.Reference;/** * 封裝引用對象的基類 * @author CodeingSnail * * @param <T> */public abstract class ReferenceObject<T>{public Reference<T> ref;protected abstract T getInstance();protected abstract Reference<T> getReference(T t);/* * 擷取引用對象及弱引用 */private T getRefrenceAndInstance(){T t = getInstance();getReference(t);return t;}/** * 擷取被引用的對象 * @return */public T get(){if(ref == null){return getRefrenceAndInstance();}T t = ref.get();if(t == null){return getRefrenceAndInstance();}return t;}/** * 清Null 物件的引用。回收對象 */public void recycle() {if(ref != null){ref.clear();ref = null;}}}
import java.lang.ref.Reference;import java.lang.ref.SoftReference;import javax.swing.ImageIcon;/** * 引用圖片資源的類 * @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 軟引用;public class Client {private ReferenceBitmap referenceBitmap;public static void main(String[] args) {Client client = new Client();client.referenceBitmap = new ReferenceBitmap("E:\\test.png");System.out.println("圖片的高度是:" + client.referenceBitmap.get().getIconHeight());System.out.println("圖片的寬度是:" + client.referenceBitmap.get().getIconWidth());}}
在上面範例中我們先定義了一個引用的抽象類別,而且給子類提供兩個回調方法用來建立圖片對象和所須要的軟引用(也能夠是弱引用),在get()方法中擷取對象的執行個體。事實上上面的範例是一個通用的方法。我們能夠在getReference中定義我們須要的參考型別。假如我們如今已經非常明白,我們要的就是軟引用,能夠將代碼簡化例如以下:

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("圖片的高度是:" + client.referenceBitmap.get().getIconHeight());System.out.println("圖片的寬度是:" + client.referenceBitmap.get().getIconWidth());//簡化方法client.softRefrence = new SoftReference<ImageIcon>(new ImageIcon("E:\\test.png"));System.out.println("圖片的高度是:" + client.softRefrence.get().getIconHeight());System.out.println("圖片的寬度是:" + client.softRefrence.get().getIconWidth());}}
三、怎樣配合引用隊列使用我們以下來分析一下java.util包下的WeakHashMap類,開啟JDK後會發現對這個類有一個非常長的描寫敘述。我們來一起看一下大概意思。Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.這句話的大概意思是WeakHashMap的雜湊表是基於Map介面的。當中key中儲存的是value的一個弱引用。當系統回收了該key所相應的實際對象之後。WeakHashMap會自己主動刪除該key相應的key-value對。
    /**     * 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> 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繼承自WeakReference,在構造方法中能夠看到直接將key交給WeakReference並通過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 be in use by a HashIterator                        e.value = null; // Help GC                        size--;                        break;                    }                    prev = p;                    p = next;                }            }        }    }
WeakHashMap中有一個私人的expungeStaleEntries方法。會在大部分共同擁有方法中被調用,這種方法會將ReferenceQueue中全部失效的引用從Map中移除。WeakHashMap不會自己主動釋放失效的引用,僅當包括了expungeStaleEntries方法被調用的時候才會釋放。以下一個小範例來看一下WeakHashMap的使用:
public static void main(String[] args) {WeakHashMap<String, String> map = new WeakHashMap<String, String>();map.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(500);} catch (InterruptedException 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++;}}
輸出結果:
Map Size: 3123Map Size: 2null23Map Size: 2null23Map Size: 2null23Map Size: 1null2nullMap Size: 1null
上面的範例中。第一個key外部沒有強引用,則僅僅列印了一次就被回收器回收,第三個key有外部的強引用。當我們將外部參考去掉後也被記憶體回收行程回收。第二個key是被字串常量池所引用,所以一直存在。


Java中的軟(弱)引用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.