Java引用类型

     今天我们来学习一下java引用类型,java引用类型主要分为强引用、软引用、弱引用、虚引用。一、强引用

     如果一个对象被强引用,那么无论如何都不会被垃圾回收器回收,最常见的强引用就是通过new关键字创建一个对象

Person person = new Person();

    我们重写Person的finalize方法,然后手动调用System.gc(),可以看到,只有当Person对象没有被引用才会被回收

public class Person {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("person finalize method invoked");
    }
}

二、软引用

     软引用是通过SoftReference类来实现的,所有被软引用对象会在JVM抛出OutOfMemoryError前被回收。我们设置java堆内存为50M,可以看到,当内存分配不足时,被软引用的对象会被回收。

创建软引用可以指定一个队列,当被软引用对象被垃圾回收器回收时,软引用对象会加入指定队列

 

三、弱引用

     弱引用是通过WeakReference类来实现的,被弱引用的对象会随时被垃圾回收器回收。

WeakReference也可以结合ReferenceQueue来使用。

ThreadLocal的静态内部类ThreadLocalMap中的key就用到了弱引用。

 

四、虚引用

     虚引用是通过PhantomReference类来实现的,虚引用无法通过reference.get()都不能获取到被虚引用的对象。虚引用必须指定一个引用队列,当然可以为空,但是如果为空,虚引用将变得没有意义,当一个对象被回收,如果垃圾回收器发现当前对象被虚引用,那么虚引用对象会被放入指定引用队列。

public class PhantomReference<T> extends Reference<T> {

    /**
     * Returns this reference object's referent.  Because the referent of a
     * phantom reference is always inaccessible, this method always returns
     * <code>null</code>.
     *
     * @return  <code>null</code>
     */
    public T get() {
        return null;
    }

    /**
     * Creates a new phantom reference that refers to the given object and
     * is registered with the given queue.
     *
     * <p> It is possible to create a phantom reference with a <tt>null</tt>
     * queue, but such a reference is completely useless: Its <tt>get</tt>
     * method will always return null and, since it does not have a queue, it
     * will never be enqueued.
     *
     * @param referent the object the new phantom reference will refer to
     * @param q the queue with which the reference is to be registered,
     *          or <tt>null</tt> if registration is not required
     */
    public PhantomReference(T referent, ReferenceQueue<? super T> q) {
        super(referent, q);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值