16 Memory Management

Version 41

Memory management allows us to create new objects and get rid of them; or more generally, to allocate chunks of memory — make them available to a program — and deallocate them — the program has no further use for it.

Early languages and memory management:

16.1 Explicit Memory Management

The Free List

Evaluation

Advantages of Explicit Memory Management

Disadvantages

Using a Node Pool

Remarks

16.2 Automatic Memory Management

A. Reference Counting

B. Garbage Collection (GC)

GC preserves the live objects while reclaiming the space of all unused objects.

B. 1. Mark and Sweep GC

B. 2. Copying GC (Copy and Compact)

Remarks on Copying GC

  1. The address of every live object has changed, but the programmer doesn't need to know or care about it, because all the pointers were updated to the objects' new addresses.
  2. All live objects are now concentrated in the lower part of the former to-space, which is now the from-space. The memory has been compacted. Further, objects that are connected by pointers are now close together in memory. This compaction is beneficial to virtual memory and cache, which work best when related data are at nearby addresses.
  3. The memory allocator doesn't have to hunt for a right-sized chunk. It just advances the allocation pointer by the amount needed. When it can't do that, it's time for a new GC.
  4. The time it takes for GC is remarkably short, since most of the former from-space was garbage (typically about 80%). The time is proportional to the space used by live objects, which is much less than the size of the heap.
  5. So, which is really more efficient, explicit memory management or automatic memory management? Copy/compact GC runs in time proportional to the live object space. Explicit memory management runs in time proportional to the number of objects deleted. Since the heap is usually mostly garbage, the surprising result is that copy and compact GC is typically faster than explicit memory management!
  6. Generational GC offers additional speedup. (What's this? …)
  7. Nevertheless, even a short pause for GC may be unacceptable for some "real-time" applications.
  8. In Exercise 16.11, p. 462: Note that Sun's Java license says it is not to be used for such applications!

Footnotes


  1. Revision history:
    • Version 4, 2010 Nov 30. Converted to markdown.
    • Version 3, 2009 Nov 30. Converted to RST.
    • Version 2, 2007 Nov 26: HTMLized about half.
    • Version 1: 2006, plain text.