How does catching an OutOfMemoryException work?

后端 未结 5 1038
再見小時候
再見小時候 2021-01-01 11:29

I am a little bit confused about the fact that we can just catch an OutOfMemoryException using a try/catch block.

Given the following code:



        
5条回答
  •  隐瞒了意图╮
    2021-01-01 11:39

    Your OutOfMemory() method creates data structure (the List) that is local to the method's scope. While your thread of execution is inside the OutOfMemory method, the current stack frame is considered the GC root for the List. Once your thread ends up in the catch block, the stack frame has been popped and the list has effectively become unreachable. Therefore the garbage collector determines that it can safely collect the list (which it does as you have observed in your memory graph).

提交回复
热议问题