强引用 Object obj = new Object()
软引用 内存不足时回收
弱引用 GC到来时回收
虚引用 GC回收时会得到一个通知
测试软引用
private void testSoftReference() {
User user =new User(1,"xiaoming");
SoftReference<User> softReference = new SoftReference<User>(user);
user =null;
System.out.println(softReference.get());
System.gc();
System.out.println("after gc");
System.out.println(softReference.get());
}
打印结果
2021-03-25 10:31:52.813 7308-7308/com.example.myapplication I/System.out: com.example.myapplication.User@a6abbf4
2021-03-25 10:31:52.814 7308-7308/com.example.myapplication I/System.out: after gc
2021-03-25 10:31:52.814 7308-7308/com.example.myapplication I/System.out: com.example.myapplication.User@a6abbf4
private void testWeakReference() {
User user1 =new User(2,"xiaoming");
WeakReference<User> weakReference = new WeakReference<User>(user1);
user1 =null;
System.out.println(weakReference.get());
System.gc();
System.out.println("after gc");
System.out.println(weakReference.get());
}
2021-03-25 11:10:57.684 8191-8191/com.example.myapplication I/System.out: com.example.myapplication.User@a6abbf4
2021-03-25 11:10:57.684 8191-8191/com.example.myapplication I/System.out: after gc
2021-03-25 11:10:57.684 8191-8191/com.example.myapplication I/System.out: null
private void testPhantomReference() {
try {
ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
Object object = new Object();
PhantomReference phantomReference = new PhantomReference(object, referenceQueue);
object = null;
System.out.println("object " + object); //null
System.out.println("phantomReference " + referenceQueue.poll());//null
System.gc();
Thread.sleep(2000);
System.out.println("referenceQueue " + referenceQueue.poll());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
2021-03-25 11:21:05.228 8515-8515/com.example.myapplication I/System.out: object null
2021-03-25 11:21:05.228 8515-8515/com.example.myapplication I/System.out: phantomReference null
2021-03-25 11:21:07.229 8515-8515/com.example.myapplication I/System.out: referenceQueue 有值 不为null 无法模拟出垃圾回收的效果
软引用:做缓存 缓存图片
弱引用:Activity 内存泄露 使用弱引用
虚引用:没有太多用处