Middle+
Rääkige prügikoristaja (Garbage Collector) töömeetoditest.
sobes.tech AI
Vastus AI-lt
Garbage collector is an automatic memory management process that frees memory occupied by objects that are no longer used by the program.
Main methods of garbage collector operation:
-
Reference Counting:
- Each object has a counter that keeps track of the number of references to it.
- When a reference to an object is created, the counter increases.
- When a reference disappears (e.g., a variable goes out of scope), the counter decreases.
- When the counter reaches zero, the object is considered unreachable and its memory is freed.
- Problems: Cannot handle cyclic references where two or more objects reference each other but are unreachable from outside.
-
Tracing Garbage Collector:
- Works in two phases: marking and sweeping or compacting.
- Marking phase: starts from the "roots" (root set) - objects that are guaranteed accessible (e.g., global variables, stack objects). GC traverses all reachable objects from the roots and marks them as "alive".
- Sweeping phase: GC scans the entire heap. Unmarked objects are considered "garbage" and their memory is freed.
- Compacting phase (optional): after sweeping, GC can move "alive" objects to eliminate memory fragmentation.
- Advantages: Can handle cyclic references.
- Disadvantages: Can cause pauses in program execution (stop-the-world) while GC runs.
Common algorithms for tracing garbage collectors:
- Mark-and-Sweep: Marks live objects, then collects garbage.
- Mark-and-Compact: Marks live objects, then moves them for defragmentation.
- Copying: Divides the heap into two halves. During collection, GC copies live objects from one half to the other, then frees the original half.
- Generational: Based on the hypothesis that most objects die young. The heap is divided into generations (e.g., young and old). GC collects garbage more frequently in the young generation, leading to shorter pauses.
The specific method depends on the programming language used and its implementation. For example, Java and C# use different types of generational tracing collectors. Python traditionally used reference counting with an additional mechanism for detecting cyclic references, and newer versions also incorporate elements of tracing collection.