Are WeakHashMap cleared during a full GC?

前端 未结 3 1331
遥遥无期
遥遥无期 2021-02-14 06:12

I encountered some troubles with WeakHashMap.

Consider this sample code:

List list = new ArrayList();

Map

        
3条回答
  •  一生所求
    2021-02-14 06:27

    Just to add a little thing to the excellent answers from Joni Salonen and berry120. It can be shown that the JIT is actually the responsible for the "variable removing" simply turning it off with -Djava.compiler=NONE. Once you turn it off, you get the OOME.

    If we want to know what is happening under the hoods, the option XX:+PrintCompilation shows the JIT activity. Using it with the code from the question the output we get is the following:

    1       java.lang.String::hashCode (64 bytes)
    2       java.lang.String::charAt (33 bytes)
    3       java.lang.String::indexOf (151 bytes)
    4       java.util.ArrayList::add (29 bytes)
    5       java.util.ArrayList::ensureCapacity (58 bytes)
    6  !    java.lang.ref.ReferenceQueue::poll (28 bytes)
    7       java.util.WeakHashMap::expungeStaleEntries (125 bytes)
    8       java.util.WeakHashMap::size (18 bytes)
    1%      WeakHM::main @ 63 (126 bytes)
    Map size 0
    

    The last compilation (with the @ flag) is a OSR (On Stack Replacement) compilation (check https://gist.github.com/rednaxelafx/1165804#osr for further details). In simple words, it enables the VM to replace a method while it is running and it is used to improve performance of Java methods stuck in loops. I would guess that after this compilation is triggered, the JIT removes the variables that are no longer used.

提交回复
热议问题