How does the GC update references after compaction occurs

后端 未结 3 1319
盖世英雄少女心
盖世英雄少女心 2020-12-11 01:02

The .NET Garbage Collector collects objects (reclaims their memory) and also performs memory compaction (to keep memory fragmentation to minimum).

I am wondering, si

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 01:49

    For simplicity, I'll assume a stop-the-world GC in which no objects are pinned, every object gets scanned and relocated on every GC cycle, and none of the destinations overlap any of the sources. In actuality, the .NET GC is a bit more complicated, but this should give a good feel for how things work.

    Each time a reference is examined, there are three possibilities:

    1. It's null. In that case, no action is required.

    2. It identifies an object whose header says it's something other than a relocation marker (a special kind of object described below). In that case, move the object to a new location and replace the original object with a three-word relocation marker containing the new location, the old location of the object which contains the just-observed reference to the present object, and the offset within that object. Then start scanning the new object (the system can forget about the object that was being scanned for the moment, since it just recorded its address).

    3. It identifies an object whose header says it's a relocation marker. In that case, update the reference being scanned to reflect the new address.

    Once the system finishes scanning the present object, it can look at its old location to find out what it was doing before it started scanning the present object.

    Once an object has been relocated, the former contents of its first three words will be available at its new location and will no longer be needed at the old one. Because the offset into an object will always be a multiple of four, and individual objects are limited to 2GB each, only a fraction of all possible 32-bit values would be needed to hold all possible offsets. Provided that at least one word in an object's header has at least 2^29 values it can never hold for anything other than an object-relocation marker, and provided every object is allocated at least twelve bytes, it's possible for object scanning to handle any depth of tree without requiring any depth-dependent storage outside the space occupied by old copies of objects whose content is no longer needed.

提交回复
热议问题