Junior — Middle
How does automatic garbage collection of unused objects occur in a managed program execution system?
sobes.tech AI
Answer from AI
Automatic collection of unused objects in memory in managed execution systems is called garbage collection. In Python, this is implemented using several mechanisms:
-
Reference counting: each object keeps track of the number of references to it. When the count reaches zero, the object is immediately deleted.
-
Cyclic garbage collector (gc module): to detect and remove objects that reference each other but are inaccessible from the program (cycles), an additional graph traversal algorithm is used.
Thus, Python automatically frees memory from objects that are no longer used, without the need for manual memory management.
Example:
import gc
class A:
def __init__(self):
self.ref = None
# Create a cyclic reference
obj1 = A()
obj2 = A()
obj1.ref = obj2
obj2.ref = obj1
# Remove external references
del obj1
del obj2
# Cyclic collector will free the memory
gc.collect()