Java中的强引用,软引用,弱引用,虚引用的作用介绍
作者:孙中明 时间:2023-08-27 11:03:28
1.强引用( Strong Reference )
最普遍的引用:Object obj=new Object()
抛出OutOfMemoryError
终止程序也不会回收具有强引用的对象
通过将对象设置为null来弱化引用,使其被回收
2.软引用( Soft Reference )
对象处在有用但非必须的状态
只有当内存空间不足时,GC会回收该引用的对象的内存
可以用来实现高速缓存
String str=new String( original: "abc"); //强引用
SoftReference<String> softRef=new SoftReference<String>(str);//软引用
3.弱引用( Weak Reference )
非必须的对象,比软引用更弱一些
GC时会被回
被回收的概率也不大,因为GC线程优先级比较低
适用于引用偶尔被使用且不影响垃圾收集的对象
string str=new String( original: "abc"y ;
weakReference<String> abcweakRef = new weakReference<String>(str);
4.虚引用( PhantomReference )
不会决定对象的生命周期
任何时候都可能被垃圾收集器回收
跟踪对象被垃圾收集器回收的活动,起哨兵作用必须和引用队ReferenceQueue
联合使用
String str=new String( original: "abc");
ReferenceQueue queue = new ReferenceQueue( ) ;
PhantomReference ref = new PhantomReference(str, queue);
5.强引用>软引用>弱引用>虚引用
来源:https://blog.51cto.com/hiszm/5015387
标签:Java,强引用,软引用,弱引用,虚引用
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java Vector实现班级信息管理系统
2023-11-25 03:09:09
![](https://img.aspxhome.com/file/2023/3/60233_0s.jpg)
基于java ssm springboot实现选课推荐交流平台系统
2023-06-30 08:22:25
![](https://img.aspxhome.com/file/2023/5/88065_0s.png)
详解关于Android Studio中安装和gradle的一些坑
2023-06-10 05:58:30
![](https://img.aspxhome.com/file/2023/8/120048_0s.png)
Java中Request请求转发详解
2021-05-25 20:53:42
![](https://img.aspxhome.com/file/2023/8/61538_0s.png)
Java Excel透视表相关操作实现代码
2022-02-27 00:11:01
![](https://img.aspxhome.com/file/2023/8/65218_0s.png)
cmake跨平台构建工具的学习笔记
2023-02-04 17:40:14
![](https://img.aspxhome.com/file/2023/3/129543_0s.png)
SpringMVC加载控制与Postmand的使用和Rest风格的引入及RestFul开发全面详解
2021-10-14 16:45:44
![](https://img.aspxhome.com/file/2023/5/79815_0s.png)
c# Invoke和BeginInvoke 区别分析
2022-09-03 15:20:49
![](https://img.aspxhome.com/file/2023/7/126067_0s.jpg)
Netty解决 TCP 粘包拆包的方法
2023-03-09 14:39:06
![](https://img.aspxhome.com/file/2023/1/76631_0s.png)
Android实现京东App分类页面效果
2023-05-07 02:53:49
![](https://img.aspxhome.com/file/2023/7/138727_0s.jpg)
C# 特殊的string类型详解
2022-02-10 14:11:59
C#序列化与反序列化实例
2023-05-05 21:05:27
Android使用系统自带的相机实现一键拍照功能
2023-06-05 10:27:23
![](https://img.aspxhome.com/file/2023/0/137840_0s.png)
Java线程并发访问代码分析
2022-08-15 17:42:08
![](https://img.aspxhome.com/file/2023/6/113256_0s.jpg)
Spring+Vue整合UEditor富文本实现图片附件上传的方法
2022-09-27 10:36:13
![](https://img.aspxhome.com/file/2023/3/78033_0s.png)
c#对象反序列化与对象序列化示例详解
2022-08-19 16:32:54
![](https://img.aspxhome.com/file/2023/1/106471_0s.jpg)
Java实现在线五子棋对战游戏(人机对战)
2023-01-10 19:07:29
![](https://img.aspxhome.com/file/2023/6/74896_0s.gif)
Java关键字详解之final static this super的用法
2022-01-19 09:24:39
![](https://img.aspxhome.com/file/2023/3/62123_0s.png)
Android设计模式系列之工厂方法模式
2023-08-16 19:10:17
![](https://img.aspxhome.com/file/2023/8/94978_0s.jpg)
C#如何通过匿名类直接使用访问JSON数据详解
2023-07-20 12:31:53
![](https://img.aspxhome.com/file/2023/7/67057_0s.jpg)