强引用:
User user = new User();
String str = "hello";
如果一个对象具有强引用,那垃圾回收器绝不会回收它。当内存不足时,宁可抛OutOfMemoryError错误。
只有显式将其设置为null,或超出对象生命周期,这个对象才可以被回收。
备注:可使用完对象后设置为null
软引用:
SoftReference<String> sr = new SoftReference<String>(new String("hello"));
System.out.println(sr.get());
对于软引用关联着的对象,只有在内存不足的时候JVM才会回收该对象。
可以很好地用来解决OOM问题,并且这个特性很适合用来实现缓存:比如网页缓存、图片缓存等。
弱引用:
WeakReference<String> sr = new WeakReference<String>(new String("hello"));
System.out.println(sr.get()); //输出hello
System.gc(); //通知JVM的gc进行垃圾回收
System.out.println(sr.get()); // 输出null
当JVM进行垃圾回收时,无论内存是否充足,都会回收被弱引用关联的对象。
虚引用:
虚引用和前面的软引用、弱引用不同,它并不影响对象的生命周期。在java中用java.lang.ref.PhantomReference类表示。如果一个对象与虚引用关联,则跟没有引用与之关联一样,在任何时候都可能被垃圾回收器回收。
ReferenceQueue<String> queue = new ReferenceQueue<String>();
PhantomReference<String> pr = new PhantomReference<String>(new String("hello"), queue);
System.out.println(pr.get());
虚引用必须和引用队列关联使用,当垃圾回收器准备回收一个对象时,如果发现它有虚引用,就会把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。如果程序发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。
利用软引用和弱引用解决OOM问题:
设计思路是:用一个HashMap来保存图片的路径 和 相应图片对象关联的软引用之间的映射关系,在内存不足时,JVM会自动回收这些缓存图片对象所占用的空间,从而有效地避免了OOM的问题。在Android开发中对于大量图片下载会经常用到。
private Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
public void addBitmapToCache(String path) {
// 强引用的Bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(path);
// 软引用的Bitmap对象
SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap);
// 添加该对象到Map中使其缓存
imageCache.put(path, softBitmap);
}
public Bitmap getBitmapByPath(String path) {
// 从缓存中取软引用的Bitmap对象
SoftReference<Bitmap> softBitmap = imageCache.get(path);
// 取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
Bitmap bitmap = softBitmap.get();
if (bitmap == null) {
// 如果bitmap为null,说明已经被回收,这样我们需要重新获取
bitmap = BitmapFactory.decodeFile(path);
}
return bitmap;
}
JVM四大引用(强、弱、软、虚)
于 2020-08-23 16:02:48 首次发布