Lecture - Imperative Programming TT23, XI


  • Reference counting
    • Associate a counter with each object
    • Increase when attaching to a reference
    • Decrease when detaching from a reference
    • If count is zero, then can garbage collect
    • Reference counting cannot deal with cyclic references
    • The solution is to free memory held by “unreachable code”, this can be done with a technique called “mark and sweep”
  • Internalisation
    • An optimisation technique used for efficiently using memory when you don’t care about object identity
    • Create a hash map that contains already existing “equal” instances of a given class and use those instead
    • Can lead to memory leaks
    • Weak reference: like a normal reference but doesn’t affect if an object will be garbage collected
    • These can be used to solve memory leaks when using internalisation.
  • Finalisers
    • finalize() is called before an object is garbage collected, e.g. could be used for closing files
    • Better to handle this explictly in the code, like adding a specific method for releasing resources

Flashcards

When does reference counting increase or decrease the count associated with each object?

  • Increase, attaching to a reference
  • Decrease, deatching from a reference

In what situation does reference counting fail, and what technique can be used to fix this?

When there are cyclic references, using a technique called “mark and sweep”.

What is the “internalisation” technique?

An optimisation technique used for efficieciently using memory, where you create a hashmap of objects that will “act” the same and reuse them.

What is a weak reference?

A reference that doesn’t affect if an object will be garbage collected, might suddenly point to null.

When is finalize() called in Scala?

Just before an object is garbage collected.