在JDK 1.2以前的版本中,若一个对象不被任何变量引用,那么程序就无法再使用这个对象。也就是说,只有对象处于可触及(reachable)状态,程序才能使用它。从JDK 1.2版本开始,把对象的引用分为4种级别,从而使程序能更加灵活地控制对象的生命周期。这4种级别由高到低依次为:强引用、软引用、弱引用和虚引用
public class SoftTest{ public static void main(String[] args) { Object ref = new Object();//ref是Object对象的强引用 //将一个软引用指向对象,此时Object对象有两个引用 SoftReference<Object> sf = new SoftReference<Object>(ref); ref = null;//去除对象的强引用 System.gc();//gc只有在内存不足是才会回收软引用对象 } }
public class WeakTest{ public static void main(String[] args) { Object ref = new Object();//ref是Object对象的强引用 //将一个弱引用指向对象,此时Object对象有两个引用 WeakReference<Object> wf = new WeakReference<Object>(ref); ref = null;//去除对象的强引用 System.gc();//gc对弱引用对象进行回收 } }
public class PhantomTest{ public static void main(String[] args) { Object ref = new Object();//ref是Object对象的强引用 //将一个幽灵引用指向对象,PhantomReference必须与ReferenceQueue一同使用 PhantomReference<Object> pf = new PhantomReference<Object>(ref, new ReferenceQueue<Object>()); System.out.println(pf.get()); } }
public abstract class AsyncQueryHandler extends Handler { private static final String TAG = "AsyncQuery"; private static final boolean localLOGV = false; private static final int EVENT_ARG_QUERY = 1; private static final int EVENT_ARG_INSERT = 2; private static final int EVENT_ARG_UPDATE = 3; private static final int EVENT_ARG_DELETE = 4; /* package */ final WeakReference<ContentResolver> mResolver;ImageLoader使用WeakReference做缓存处理
public abstract class BaseMemoryCache implements MemoryCache { /** Stores not strong references to objects */ private final Map<String, Reference<Bitmap>> softMap = Collections.synchronizedMap(new HashMap<String, Reference<Bitmap>>()); ...... @Override protected Reference<Bitmap> createReference(Bitmap value) { return new WeakReference<Bitmap>(value); }基本可以这么说
private static class MyHandler extends Handler { private final WeakReference<SampleActivity> mActivity; public MyHandler(SampleActivity activity) { mActivity = new WeakReference<SampleActivity>(activity); } @Override public void handleMessage(Message msg) { SampleActivity activity = mActivity.get(); if (activity != null) { // ... } } }不会内存泄露,Handler中也能访问到activity中的非静态变量
欢迎扫描二维码,关注公众号