liveBook · Manning

Locals clearing

As explained in Clojure: The Essential Reference

Locals clearing is a compiler optimization that nulls references held by a function after one-time execution so the referenced resources can be reclaimed.

Locals clearing is a compiler optimization that nulls references held by a one-time function after execution, allowing the JVM to reclaim referenced resources sooner. section 2.1.3

The optimization depends on three conditions:

  • The function body must be intended to execute only once. section 2.1.3
  • Marking a function as ^:once fn* promises the compiler that it will not run again. section 2.1.3
  • After execution, compiled references to the lambda can be set to null, reducing the time resources remain reachable. section 2.1.3

A once-only future body

(defmacro future [& body] `(future-call (^{:once true} fn* [] ~@body))) The metadata marks the generated function as one-time execution code, enabling locals clearing. section 2.1.3

How Clojure: The Essential Reference covers it

How deep it goes
Explains the once-only contract and compiled-reference nulling, while deferring implementation details to the compiler and JVM.
Examples
Uses the future macro, future-call, and a zero-argument ^:once fn* function.
What it assumes
Assumes familiarity with Clojure functions and macros, while explaining the once-only promise behind the optimization.
What you can do after
Apply ^:once fn* when a generated function is guaranteed to execute only once and should release references promptly.
How it connects
Connects fn*, fn, future, macros, compiler optimization, and JVM resource reclamation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.