WeakHashMap garbage collection principle

introduce

WeakHashMap naturally associates with HashMap. Indeed, WeakHashMap is a hash table like HashMap, and the storage content is also a key-value pair. The functions similar to HashMap will not be expanded. This article focuses on how does WeakHashMap recover data?

Garbage Collection Principles

Talking about the WeakHashMap recycling principle starts with WeakReference (weak reference). Everyone knows that the premise of GC recycling an object is that if there is no valid reference to the object in the reference from the root set, the object can be recycled. The valid reference here does not include WeakReference, although weak references can be used to access objects, but Weak references are not taken into account during garbage collection, and only objects pointed to by weak references will still be collected by GC.
So how is WeakHashMap associated with WeakReference?
Let's take a look at the implemented code.

WeakHashMap Entry

We all know that there is an Entry array in the HashMap implementation, and WeakHashMap also has an Entry array, but this Entry is somewhat different from that Entry. The Entry of WeakHashMap inherits WeakReference. In this way, the entire Entry is a WeakReference. Let's take a look at the construction method of Entry and call super(key, queue), which is to call this construction method.

WeakReference

There are two parameters, one key and one queue. This key is the key value stored in WeakHashMap. This queue is the ReferenceQueue created in WeakHashMap.

WeakHashMap ReferenceQueue

那这个ReferenceQueue是干嘛的呢?了解GC的朋友可能知道,当GC某个对象时,如果有此对象上还有弱引用与其关联,会将WeakReference对象与Reference类的pending引用关联起来,然后由Reference Handler线程将该插入ReferenceQueue队列。
也就是说当Entry中的key被GC时,会将Entry放入到ReferenceQueue中,WeakHashMap就能个通过ReferenceQueue中的Entry了解到哪些key已经被GC,或者即将马上被GC,起到了通知的作用。

了解了以上信息后,我们再看下面这段代码:


WeakHashMap expungeStaleEntries

这段代码就是WeakHashMap用来处理ReferenceQueue中被GC的key所关联的Entry相关数据,通过从queue中poll出相关的Entry,然后去WeakHashMap的entry数组中找到索引,然后从对应的链中去掉相关的Entry,最后将value赋值为空(Help GC),到这里就完成了相关数据的清理。
但是谁来触发expungeStaleEntries方法呢?有多个方法都可以触发,如put、get、remove、size等方法都能够触发相关的逻辑。

误区

是不是使用了WeakHashMap就一定没有问题了呢?当然不是,如果没有触发expungeStaleEntries这个方法依然会导致内存泄漏,比如初始化好WeakHashMap中相关数据后,一直不调用put、get、remove、size等相关方法,也是不能够正常回收的。

总结

了解了WeakHashMap原理之后,使用起来是不是更加得心应手了呢。



Author: Disheng_YinQi
Link: https://www.jianshu.com/p/6904d632549f
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326846421&siteId=291194637