强引用、软引用和弱引用。
Student strongReference = new Student();
WeakReference<Student> weakReference = new WeakReference<>(strongReference);
相似地
Student strongRef = new Student();
SoftReference<Student> softReference = new SoftReference<>(strongRef);
在垃圾回收期间,如果堆中的对象对它有强引用,那么它会存活下来,如果它没有强引用但有弱引用,那么它就不会存活。当对象传递到生命周期管理器上下文之外时,它用于避免泄漏。
软引用类似于弱引用,但它们会在垃圾回收周期中幸存下来,直到内存有足够的可用为止。
一个对象是轻轻触手可及如果没有强引用并且有软引用。由于仅具有弱引用的对象有资格进行垃圾收集,而另一方面仅具有软引用的对象更容易在垃圾收集中生存(与弱引用相比),因此
没有强引用而只有软引用或弱引用的对象是软可达的
仅具有 WeakReference 而没有强引用或软引用的对象是每周可访问的
具有至少一个强引用(带或不带任何软引用或弱引用)的对象是强可达的。
以下两种情况堆中的对象都是软可达的。
Student stRef = new Student();
SoftReference <Student> sfRef = new SoftReference<>(stRef);
stRef = null;
Or
SoftReference <Student> sfRef = new SoftReference<>(new Student());
使用对象get()
方法已被使用,但我们知道它为您提供了强有力的参考。
假设你有
Student strongReference = new Student();
SoftReference<Student> softReference = new SoftReference<>(strongReference);
strongReference = null; // object in heap is softly reachable now
Student anotherStrongReference = softReference.get();
if(anotherStrongReference != null){
// you have a strong reference again
}
因此,避免分配从返回的非空对象get()
对静态或实例变量的弱引用或软引用的方法,否则它只会破坏其中任何一个的用法。使用其中任何一个的最佳方法是如果需要以弱引用或软引用的形式存储静态或实例变量。当你需要使用时get()
检查不为空并仅用作局部变量。如果可能的话,仅传递给其他方法弱引用或软引用。
WeakReference 和 SoftReference 之间的区别在各个链接中都有很好的解释,其中一个链接是:https://stackoverflow.com/a/299702/504133 https://stackoverflow.com/a/299702/504133
附: WeakReference 和 SoftReference 对象类型的引用是强引用的,它是弱或软可达的包装对象,以防没有可用的强引用(可以通过使用检索该对象get()
).
WeakReference <Student> weakRefOfStudent = new WeakReference<>(new Student());
weakRefOfStudent
是类型的强引用WeakReference.java
堆中类型为 Student 的对象每周可访问。该对象可以通过以下方式访问weakRefOfStudent.get()
。如果它已被垃圾收集,则它可能为空,也可能不为空。
这只是为了澄清可能出现的疑虑。