Java中的SoftReference
即對象的軟引用。如果一個對象具有軟引用,記憶體空間足夠,垃 圾回收器就不會回收它;如果記憶體空間不足了,就會回收這些對象的記憶體。只要記憶體回收行程沒有回收它,該對象就可以被程式使用。軟引用可用來實現記憶體敏感的高 速緩衝。使用軟引用能防止記憶體泄露,增強程式的健壯性。
SoftReference的特點是它的一個執行個體儲存對一個Java對象的軟引用, 該軟引用的存在不妨礙垃圾收集線程對該Java對象的回收。也就是說,一旦SoftReference儲存了對一個Java對象的軟引用後,在垃圾線程對 這個Java對象回收前,SoftReference類所提供的get()方法返回Java對象的強引用。另外,一旦垃圾線程回收該Java對象之 後,get()方法將返回null
用Map集合緩衝軟引用的Bitmap對象
Map<String, SoftReference<Bitmap>> imageCache = new new HashMap<String, SoftReference<Bitmap>>();
//強引用的Bitmap對象
Bitmap bitmap = BitmapFactory.decodeStream(InputStream);
//軟引用的Bitmap對象
SoftReference<Bitmap> bitmapcache = new SoftReference<Bitmap>(bitmap);
//添加該對象到Map中使其緩衝
imageCache.put("1",softRbitmap);
..
.
//從緩衝中取軟引用的Bitmap對象
SoftReference<Bitmap> bitmapcache_ = imageCache.get("1");
//取出Bitmap對象,如果由於記憶體不足Bitmap被回收,將取得空
Bitmap bitmap_ = bitmapcache_.get();
如果程式中需要從網上載入大量的圖片 這時就考慮採用在sdcard上建立臨時檔案夾緩衝這些圖片了
public class BitmapCache {
static private BitmapCache cache;
/** 用於Chche內容的儲存 */
private Hashtable<Integer, MySoftRef> hashRefs;
/** 垃圾Reference的隊列(所引用的對象已經被回收,則將該引用存入隊列中) */
private ReferenceQueue<Bitmap> q;
/**
* 繼承SoftReference,使得每一個執行個體都具有可識別的標識。
*/
private class MySoftRef extends SoftReference<Bitmap> {
private Integer _key = 0;
public MySoftRef(Bitmap bmp, ReferenceQueue<Bitmap> q, int key) {
super(bmp, q);
_key = key;
}
}
private BitmapCache() {
hashRefs = new Hashtable<Integer, MySoftRef>();
q = new ReferenceQueue<Bitmap>();
}
/**
* 取得緩衝器執行個體
*/
public static BitmapCache getInstance() {
if (cache == null) {
cache = new BitmapCache();
}
return cache;
}
/**
* 以軟引用的方式對一個Bitmap對象的執行個體進行引用並儲存該引用
*/
private void addCacheBitmap(Bitmap bmp, Integer key) {
cleanCache();// 清除垃圾引用
MySoftRef ref = new MySoftRef(bmp, q, key);
hashRefs.put(key, ref);
}
/**
* 依據所指定的drawable下的圖片資源ID號(可以根據自己的需要從網路或本地path下擷取),重新擷取相應Bitmap對象的執行個體
*/
public Bitmap getBitmap(int resId, Context context) {
Bitmap bmp = null;
// 緩衝中是否有該Bitmap執行個體的軟引用,如果有,從軟引用中取得。
if (hashRefs.containsKey(resId)) {
MySoftRef ref = (MySoftRef) hashRefs.get(resId);
bmp = (Bitmap) ref.get();
}
// 如果沒有軟引用,或者從軟引用中得到的執行個體是null,重新構建一個執行個體,
// 並儲存對這個建立執行個體的軟引用
if (bmp == null) {
// 傳說decodeStream直接調用JNI>>nativeDecodeAsset()來完成decode,
// 無需再使用java層的createBitmap,從而節省了java層的空間。
bmp = BitmapFactory.decodeStream(context.getResources()
.openRawResource(resId));
this.addCacheBitmap(bmp, resId);
}
return bmp;
}
private void cleanCache() {
MySoftRef ref = null;
while ((ref = (MySoftRef) q.poll()) != null) {
hashRefs.remove(ref._key);
}
}
/**
* 清除Cache內的全部內容
*/
public void clearCache() {
cleanCache();
hashRefs.clear();
System.gc();
System.runFinalization();
}
}