强引用、软引用和弱引用。
Student strongReference = new Student();
WeakReference<Student> weakReference = new WeakReference<>(strongReference);
同样
Student strongRef = new Student();
SoftReference<Student> softReference = new SoftReference<>(strongRef);
在垃圾回收过程中,如果堆中的对象有强引用,那么它就会存活,如果它没有强引用但有弱引用,那么它就不会存活。当对象在生命周期管理器上下文中传递出去时,它用于避免泄漏。
SoftReference 类似于弱引用,但它们会在垃圾回收周期中存活下来,直到内存充足为止。
如果没有强引用并且有软引用,则对象是软可达。由于只有弱引用的对象有资格进行垃圾收集,另一方面,只有软引用的对象更容易在垃圾收集中幸存下来(与弱引用相比),因此
没有强引用且只有软引用或弱引用的对象是软可达的
只有 WeakReference 而没有 Strong 或 soft 引用的对象是 Weekly Reachable
具有至少一个强引用(有或没有任何软引用或弱引用)的对象是强可达的。
以下两种情况堆中的对象都是软可达的。
Student stRef = new Student();
SoftReference <Student> sfRef = new SoftReference<>(stRef);
stRef = null;
或者
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
}
因此,请避免将 Weak 或 Soft 引用的 get() 方法返回的非 null 对象分配给静态或实例变量,否则它只会破坏其中任何一个的使用。如果需要,最好以弱引用或软引用的形式使用这些方法中的任何一个来存储静态或实例变量。当您需要使用 get() 时,请检查 not null 并仅用作本地变量。如果可能,只传递给其他方法,仅弱引用或软引用。
WeakReference 和 SoftReference 之间的区别在各种链接中得到了很好的解释,其中一个链接是:
https://stackoverflow.com/a/299702/504133
附: WeakReference 和 SoftReference 类型对象的引用是强引用的,它是弱或软可访问的包装对象,以防没有强引用可用(可以使用get() 检索对象)。
WeakReference <Student> weakRefOfStudent = new WeakReference<>(new Student());
weakRefOfStudent 是WeakReference.java 类型的强引用,并且学生类型的堆中的对象每周可访问。 weakRefOfStudent.get() 可以访问该对象。如果它是否已被垃圾收集,它可能为空,也可能不为空。
这只是为了澄清可能出现的疑问。