linux空间做网站,中国宣布入境最新消息2023,网站制作容易吗怎么样,wordpress倒闭汉化组首先分别介绍一下这几种引用 强引用#xff1a; 只要能通过GC ROOT根对象引用链找到就不会被垃圾回收器回收#xff0c;当所有的GC Root都不通过强引用引用该对象时#xff0c;才能被垃圾回收器回收。
软引用#xff08;SoftReference#xff09;#xff1a; 当只有软引…
首先分别介绍一下这几种引用 强引用 只要能通过GC ROOT根对象引用链找到就不会被垃圾回收器回收当所有的GC Root都不通过强引用引用该对象时才能被垃圾回收器回收。
软引用SoftReference 当只有软引用引用该对象时在垃圾回收之后内存仍然不足会再次发起垃圾回收这时会回收掉软引用对象我们可以配合引用队列来释放软引用自身。
弱引用 当发生垃圾回收时无论内存是否够用只有软引用的对象都会被垃圾回收器回收
虚引用 必须配合引用队列使用主要配合 ByteBuffer 使用被引用对象回收时会将虚引用入引用队列 由 Reference Handler 线程调用虚引用相关方法释放直接内存。
终结器引用 无需手动编码但其内部配合引用队列使用在垃圾回收时终结器引用入队被引用对象 暂时没有被回收再由 Finalizer 线程通过终结器引用找到被引用对象并调用它的 finalize 方法第二次 GC 时才能回收被引用对象
实例
强引用 首先我们设置内存大小为20MB public class Demo2_3 {private static final int _4MB 4 * 1024 * 1024;public static void main(String[] args) throws IOException {ArrayListbyte[] list new ArrayList();for (int i 0; i 5; i) {list.add(new byte[_4MB]);}System.in.read();}}启动main因为强引用无法被垃圾回收会发生内存溢出报错内存不足无法启动
弱引用 应用场景
public class Demo2_4 {private static final int _4MB 4 * 1024 * 1024;//软引用当堆内存空间不足时会回收来释放内存空间public static void main(String[] args) throws IOException {//list --- SoftReference --- byte[] list先引用了软引用对象SoftReference软引用对象SoftReference再间接引用byteListSoftReferencebyte[] list new ArrayList();for (int i 0; i 5; i) {//引用对象关联引用队列当软引用所关联的byte[]被回收时软引用自己会加入到引用队列queue中去SoftReferencebyte[] ref new SoftReference(new byte[_4MB]);System.out.println(ref.get());list.add(ref);System.out.println(list.size());}System.out.println(循环结束 list.stream());for (SoftReferencebyte[] softReference : list) {System.out.println(softReference.get());}}
}
运行 查看打印结果程序在第四次循环的时候内存不足触发了垃圾回收此时将前面的软引用的对象给回收了所以我们最后打印结果只有第五个对象不为null
同时我们还可以配合引用队列来释放软引用自身
public class Demo2_3 {private static final int _4MB 4 * 1024 * 1024;public static void main(String[] args) throws IOException {
//list --- SoftReference --- byte[] list先引用了软引用对象SoftReference软引用对象SoftReference再间接引用byteListSoftReferencebyte[] list new ArrayList();//引用队列ReferenceQueuebyte[] queue new ReferenceQueue();for (int i 0; i 5; i) {//引用对象关联引用队列当软引用所关联的byte[]被回收时软引用自己会加入到引用队列queue中去SoftReferencebyte[] ref new SoftReference(new byte[_4MB],queue);System.out.println(ref.get());list.add(ref);System.out.println(list.size());}//poll方法就是从队列中获取最先放入队列的元素移除队列//从队列中获取无用的软引用对象并移除Reference? extends byte[] poll queue.poll();while (poll ! null){list.remove(poll);poll queue.poll();}System.out.println(循环结束 list.stream());for (SoftReferencebyte[] softReference : list) {System.out.println(softReference.get());}}
}运行程序 前四次循环的软引用自身已经被释放
弱引用 应用场景举例
public class Demo2_5 {private static final int _4MB 4 * 1024 * 1024;public static void main(String[] args) {ArrayListWeakReferencebyte[] list new ArrayList();for (int i 0; i 8; i) {WeakReferencebyte[] ref new WeakReference(new byte[_4MB]);list.add(ref);for (WeakReferencebyte[] w : list) {System.out.print(w.get() );}System.out.println();}System.out.println(循环结束list.size());}
}运行程序