(Four references in java)java中的四种引用

强引用(Strong Reference)

String s = new String(""); //that’s a strong reference
s = null;
功能 :如果一个对象只有强引用,那么垃圾回收器绝对不会回收它,JVM宁愿抛出内存不足的异常也不会回收这些对象. 没有显性的释放对象,JVM时不会回收该对象的.
使用场景 :平时大部分使用的场景都是使用了强引用,比如new创建对象,反射获得一个对象等
Function:
This kind of reference makes the referenced object not eligible for GC. The JVM would rather throw out an Exception with Out Of Memory than recycle objects.JVM will recycle this object till the object become null.
Applicition:
Most of the scenes used in peacetime use Strong Reference.For example, get an object through new,or reflect

软引用(Soft Reference)

Java中提供SoftReference< A >类处理软引用
功能 :如果一个对象只具有软引用,则内存空间足够时,垃圾回收器就不会回收它
如果内存空间不足时,就会回收这些对象的内存.
使用场景 :为了内存消耗会选择使用软引用,比如缓存.
Java provide SoftReference< A > to process soft reference
Function:
if a object only used soft,GC will recycle it till the memory isn’t enough,which means the object will alive based on memory is enough.
Applicition:
In order to consume memory,just like cache.

弱引用(Weak Reference)

java中提供WeakReference类处理弱引用,
功能 :拥有更短的生命周期.只要发生GC,不管内存够不够,都会进行回收.
使用场景 :用于生命周期更短的,对内存更敏感的场景中,比如占用很大内存的Map,java就提供了
WeakHashMap使用,就会使得大Map被即使清理掉
Java provide WeakReference< A > to process weak reference
Function:
Weak has shorter life cycles, if GC happened,no matter memory enough,it will be recycled.
Applicition:
For shorter life cycles,just like Map, java offer WeakHashMap,the big Map will be cleaned up.

虚引用(Phantom Reference)

java中提供PhantomReference类来处
功能 :虚引用形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期.
那么它就和没有引用一样,在任何时候都有可能被回收.
使用场景 :他的使用场景应该在判断一个对象是否被垃圾回收了.
Java provide PhantomtReference to process phantom reference
Function:
phantom won’t decide the object’s life cycles,so phantom will be recycled in any time;
*Applicition:
*To judge whether an object is garbage collected.

猜你喜欢

转载自blog.csdn.net/weixin_43584947/article/details/83823191
今日推荐