Java 技术允许使用 finalize() 方法在垃圾收集器将对象从内存中清除出去之前做必要的清理工作。
新建一个带finalize()方法的对象MyObject
class MyObject
{
//一般开发中不用调用这个方法,本次只是为了讲课演示
@Override
protected void finalize() throws Throwable{
System.out.println(Thread.currentThread().getName()+"\t"+"---finalize method invoked....");
}
}
强引用(默认支持模式)
- 当内存不足,JVM开始垃圾回收,对于强引用的对象,就算是出现了OOM也不会对该对象进行回收,死都不收。
强引用是我们最常见的普通对象引用,只要还有强引用指向一个对象,就能表明对象还“活着”,垃圾收集器不会碰这种对象。在 Java 中最常见的就是强引用,把一个对象赋给一个引用变量,这个引用变量就是一个强引用。当一个对象被强引用变量引用时,它处于可达状态,它是不可能被垃圾回收机制回收的,即使该对象以后永远都不会被用到JVM也不会回收。因此强引用是造成Java内存泄漏的主要原因之一。
对于一个普通的对象,如果没有其他的引用关系,只要超过了引用的作用域或者显式地将相应(强)引用赋值为 null, 一般认为就是可以被垃圾收集的了(当然具体回收时机还是要看垃圾收集策略)。
package com.dongguo.threadlocal;
import java.util.concurrent.TimeUnit;
/**
* @author Dongguo
* @date 2021/9/8 0008-11:54
* @description:
*/
class MyObject {
//一般开发中不用调用这个方法
@Override
protected void finalize() throws Throwable {
System.out.println(Thread.currentThread().getName() + "\t" + "---finalize method invoked....");
}
}
public class ReferenceDemo {
public static void main(String[] args) {
MyObject myObject = new MyObject();
System.out.println("-----gc before: " + myObject);
//myObject = null;
System.gc();//手动GC
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----gc after: " + myObject);
}
}
运行结果
-----gc before: com.dongguo.threadlocal.MyObject@4b67cf4d
-----gc after: com.dongguo.threadlocal.MyObject@4b67cf4d
MyObject myObject = new MyObject()是强引用 是不会被垃圾回收的
如果想要进行垃圾回收,就要将myObject赋值为null
package com.dongguo.threadlocal;
import java.util.concurrent.TimeUnit;
/**
* @author Dongguo
* @date 2021/9/8 0008-11:54
* @description:
*/
class MyObject {
//一般开发中不用调用这个方法
@Override
protected void finalize() throws Throwable {
System.out.println(Thread.currentThread().getName() + "\t" + "---finalize method invoked....");
}
}
public class ReferenceDemo {
public static void main(String[] args) {
MyObject myObject = new MyObject();
System.out.println("-----gc before: " + myObject);
myObject = null;
System.gc();//手动GC
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----gc after: " + myObject);
}
}
运行结果
-----gc before: com.dongguo.threadlocal.MyObject@4b67cf4d
Finalizer ---finalize method invoked....
-----gc after: null
软引用
软引用是一种相对强引用弱化了一些的引用,需要用java.lang.ref.SoftReference类来实现,可以让对象豁免一些垃圾收集。
对于只有软引用的对象来说,
当系统内存充足时它 不会 被回收,
当系统内存不足时它 会 被回收。
软引用通常用在对内存敏感的程序中,比如高速缓存就有用到软引用,内存够用的时候就保留,不够用就回收!
package com.dongguo.threadlocal;
import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;
/**
* @author Dongguo
* @date 2021/9/8 0008-11:54
* @description:
*/
class MyObject {
//一般开发中不用调用这个方法
@Override
protected void finalize() throws Throwable {
System.out.println(Thread.currentThread().getName() + "\t" + "---finalize method invoked....");
}
}
public class ReferenceDemo {
public static void main(String[] args) {
SoftReference softReference = new SoftReference(new MyObject());
System.out.println("-----gc before内存够用:: " + softReference.get());
System.gc();//手动GC
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----gc after内存够用:: " + softReference.get());
}
}
运行结果
-----gc before内存够用:: com.dongguo.threadlocal.MyObject@4b67cf4d
-----gc after内存够用:: com.dongguo.threadlocal.MyObject@4b67cf4d
模拟内存不够用的情况
package com.dongguo.threadlocal;
import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;
/**
* @author Dongguo
* @date 2021/9/8 0008-11:54
* @description:
*/
class MyObject {
//一般开发中不用调用这个方法
@Override
protected void finalize() throws Throwable {
System.out.println(Thread.currentThread().getName() + "\t" + "---finalize method invoked....");
}
}
public class ReferenceDemo {
public static void main(String[] args) {
//当我们内存不够用的时候,soft会被回收的情况,设置我们的内存大小:-Xms10m -Xmx10m
SoftReference softReference = new SoftReference(new MyObject());
System.out.println("-----gc before内存够用:: " + softReference.get());
// System.gc();//手动GC
// try {
// TimeUnit.SECONDS.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println("-----gc after内存够用:: " + softReference.get());
try
{
byte[] bytes = new byte[9 * 1024 * 1024];
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("-----gc after内存不够: "+softReference.get());
}
}
}
运行结果
-----gc before内存够用:: com.dongguo.threadlocal.MyObject@4b67cf4d
-----gc after内存不够: null
Finalizer ---finalize method invoked....
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.dongguo.threadlocal.ReferenceDemo.main(ReferenceDemo.java:35)
软引用的适用场景
假如有一个应用需要读取大量的本地图片:
- 如果每次读取图片都从硬盘读取则会严重影响性能,
- 如果一次性全部加载到内存中又可能造成内存溢出。
此时使用软引用可以解决这个问题。
设计思路是:用一个HashMap来保存图片的路径和相应图片对象关联的软引用之间的映射关系,在内存不足时,JVM会自动回收这些缓存图片对象所占用的空间,从而有效地避免了OOM的问题。
Map imageCache = new HashMap();
弱引用
弱引用需要用java.lang.ref.WeakReference类来实现,它比软引用的生存期更短,
对于只有弱引用的对象来说,只要垃圾回收机制一运行,不管JVM的内存空间是否足够,都会回收该对象占用的内存。
package com.dongguo.threadlocal;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;
/**
* @author Dongguo
* @date 2021/9/8 0008-11:54
* @description:
*/
class MyObject {
//一般开发中不用调用这个方法
@Override
protected void finalize() throws Throwable {
System.out.println(Thread.currentThread().getName() + "\t" + "---finalize method invoked....");
}
}
public class ReferenceDemo {
public static void main(String[] args) {
WeakReference weakReference = new WeakReference(new MyObject());
System.out.println("-----gc before内存够用:: " + weakReference.get());
System.gc();//手动GC
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("-----gc after内存够用:: " + weakReference.get());
}
}
运行结果
-----gc before内存够用:: com.dongguo.threadlocal.MyObject@4b67cf4d
Finalizer ---finalize method invoked....
-----gc after内存够用:: null
虚引用
虚引用需要java.lang.ref.PhantomReference类来实现。
顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。 如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收, 它不能单独使用也不能通过它访问对象,虚引用必须和引用队列 (ReferenceQueue)联合使用。
虚引用的主要作用是跟踪对象被垃圾回收的状态。 仅仅是提供了一种确保对象被 finalize以后,做某些事情的机制。 PhantomReference的get方法总是返回null,因此无法访问对应的引用对象。
其意义在于:说明一个对象已经进入finalization阶段,可以被gc回收,用来实现比finalization机制更灵活的回收操作。
换句话说,设置虚引用关联的唯一目的,就是在这个对象被收集器回收的时候收到一个系统通知或者后续添加进一步的处理。
构造方法
引用队列
虚引用被回收前需要被引用队列保存下。
模拟触发GC前后虚引用的情况
package com.dongguo.threadlocal;
import java.lang.ref.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Dongguo
* @date 2021/9/8 0008-11:54
* @description:
*/
class MyObject {
//一般开发中不用调用这个方法
@Override
protected void finalize() throws Throwable {
System.out.println(Thread.currentThread().getName() + "\t" + "---finalize method invoked....");
}
}
public class ReferenceDemo {
public static void main(String[] args) {
//当我们内存不够用的时候,soft会被回收的情况,设置我们的内存大小:-Xms10m -Xmx10m
ReferenceQueue referenceQueue =new ReferenceQueue();
PhantomReference phantomReference = new PhantomReference(new MyObject(),referenceQueue);
//PhantomReference的get方法总是返回null,因此无法访问对应的引用对象。
System.out.println("-----gc before内存够用:: " + phantomReference.get());
List list = new ArrayList();
new Thread(() -> {
while (true)
{
//每过500毫秒创建一个1M的byte数组
list.add(new byte[1 * 1024 * 1024]);
try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(phantomReference.get());
}
},"t1").start();
new Thread(() -> {
while (true)
{
//通过referenceQueue查看虚对象被回收的情况
Reference reference = referenceQueue.poll();
//当内存不足前触发GC,phantomReference进入referenceQueue ,referenceQueue中有虚引用对象
if (reference != null) {
System.out.println("***********有虚对象加入队列了");
}
}
},"t2").start();
}
}
运行结果
-----gc before内存够用:: null
Finalizer ---finalize method invoked....
null
null
null
null
null
null
null
Exception in thread "t1" java.lang.OutOfMemoryError: Java heap space
at com.dongguo.threadlocal.ReferenceDemo.lambda$main$0(ReferenceDemo.java:36)
at com.dongguo.threadlocal.ReferenceDemo$$Lambda$1/1989780873.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
***********有虚对象加入队列了
虚引用对象在被回收之前会放到引用队列中,然后将引用队列清空,即堆虚引用对象进行垃圾回收
总结强引用 内存满了也不会被回收
软引用 内存满了才会被回收
弱引用执行GC就会被回收
虚引用在任何时候都有可能被回收,在回收前会将虚引用对象放到引用队列中,执行垃圾回收,引用队列就清空。