强应用-弱引用-虚引用-软引用

强引用

常见的对象赋值引用,不为空,则不会被垃圾回收器回收直到内存溢出

demo

ini 复制代码
/**
 * 强引用
 */
@Test
public void dd(){
    Object o = new Object();
    System.gc();
    assert o != null;
    o = null;
    assert o == null;
}

GC可达性检测

软引用

次于强引用,但比强引用更弱,不会被垃圾回收器回收,但内存溢出时,会被回收
适合缓存,比如图片缓存,文件缓存,数据库连接缓存,缓存数据,图片等

typescript 复制代码
    /**
     * 软引用
     */
    @Test
    public void dd1(){
        SoftReference<Object> o = new SoftReference(new Object());
        assert o != null;
    }

弱引用

弱引用,比软引用更弱只能生存到下一次垃圾收集发生之前
ThreadLocalMap 源码结构

scala 复制代码
    static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }



    /**
     * 弱引用
     */
    @Test
    public void dd2(){
        WeakReference<Object> o = new WeakReference(new Object());
        assert o != null;
    }

虚引用

资源回收回调

typescript 复制代码
    /**
     * 虚引用
     */
    @Test
    public void dd3(){
        // 创建一个引用队列
        ReferenceQueue<Object> queue = new ReferenceQueue<>();
        

    }
相关推荐
IT_陈寒2 小时前
为什么你应该学习JavaScript?
前端·人工智能·后端
淇奥72 小时前
【MyBatis-Plus】MyBatis-Plus 学习笔记
后端
_code_bear_2 小时前
OpenSpec CLI 与 OPSX 工作流说明
前端·后端·架构
用户8356290780512 小时前
使用 Python 在 PowerPoint 中添加并控制音频播放
后端·python
用户8356290780513 小时前
使用 Python 在 PowerPoint 中生成并自定义饼图与环形图
后端·python
念何架构之路3 小时前
Go语言常见并发模式
开发语言·后端·golang
Cosolar3 小时前
大模型应用开发面试 • 第4期|A2A、复杂挑战与具身智能
人工智能·后端·面试
迷渡3 小时前
聊一聊 Bun 用 Rust 重写这件事
开发语言·后端·rust
王中阳Go3 小时前
秒杀、分库分表、全链路追踪:一个电商微服务的架构全拆解
后端·go
正儿八经的少年4 小时前
Spring Boot 两种激活配置方式的作用与区别
java·spring boot·后端