Garbage Collection and Memory Management

breve includes built-in garbage collection (sometimes called GC). Garbage collection is a form of memory management in which the system detects when an object is no longer referenced by any other variable. When an object is no longer referenced by any other variable, it is an indication that the memory is no longer in use and can thus be safely deallocated.

Memory Management and Garbage Collection of Basic Types

Memory management and garbage collection of basic types happens automatically and requires no user interaction. ints, floats, matrices and vectors are passed by reference and do not require garbage collection. lists, hashes and data are automatically garbage collected when appropriate.

Memory Management and Garbage Collection of Objects

breve's garbage collection is slightly complicated by the fact that objects do not need to be referenced in memory to be "in use". An unreferened object may, for example, "come back to life" because of an all (the section called “Finding All Objects of a Given Type”) expression. Furthermore, objects in the simulated world (members of subclasses of the class "Real") may physically interact even without referencing each other in their variables. Because of these complications, garbage collection cannot be automatically enabled for all objects in a simulation.

Garbage collection for objects is thus enabled on a per-object basis and the programmer must decide when its use is appropriate. The following guidelines should generally help to decide when garbage collection is appropriate for an object:

  • the object is not a member of a subclass of Real.

  • the object does not have it's own iterate or post-iterate methods.

  • the object is not a dependency of any object that does not hold a reference to it.

A Garbage Collection Caveat: Circular References

One important caveat applies to garbage collection of both basic types and objects. The steve garbage collection scheme does not correctly deallocate memory when there are circular references. A circular reference occurs when two (or more) objects refer to each other in a circular fashion. An example of a circular reference between three objects is shown below:

When a circular reference occurs, the objects are never recognized as "unused" and are thus never deleted as they should be. Circular references thus lead to "islands" of unused memory which do not get released. This type of circular reference is rare, but if your simulation design makes use of these types of structures, you may have to explicitly overwrite variables in order to ensure that no circular references exist.