Java中的强引用,软引用,弱引用,虚引用
public static void main(String[] args) {
// 强引用
String strongReference1 = new String("abc");
// 软引用
String str1 = new String("abc");
SoftReference<String> softReference = new SoftReference<String>(str1);
// 弱引用
String str2 = new String("abc");
WeakReference<String> weakReference = new WeakReference<>(str2);
// 弱引用转强引用
String strongReference2 = weakReference.get();
// 虚引用
String str3 = new String("abc");
ReferenceQueue queue = new ReferenceQueue();
// 创建虚引用,要求必须与一个引用队列关联
PhantomReference pr = new PhantomReference(str3, queue);
}
引用类型 | 被垃圾回收时间 | 用途 | 生存时间 |
---|---|---|---|
强引用 | 从来不会(将赋值为null会被回收) | 对象的一般状态 | JVM停止运行时终止 |
软引用 | 当内存不足时 | 对象缓存 | 内存不足时终止 |
弱引用 | 正常垃圾回收时 | 对象缓存 | 垃圾回收后终止 |
虚引用 | 正常垃圾回收时 | 跟踪对象的垃圾回收 | 垃圾回收后终止 |
本文作者:碧水云天4
本文链接:https://www.cnblogs.com/smalldong/p/16340371.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步