今天我们来学习一下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);
}
}