Skip to content

2. Allocators and context parameters ​

Every constructor call Foo(...) is an allocation site. In Managed code the allocator is always Rc (reference counting). To choose another one, you put an allocator in scope.

Allocators are ordinary classes ​

They live in mini.memory (Kotlin source in stdlib/mini/memory/). What the compiler checks depends on which traits (plain Kotlin interfaces) an allocator implements:

TraitMeaningCompiler checks
Deallocatingobjects are released one by oneevery allocation is freed exactly once on every path, or moved on
Scopedeverything dies when the allocator closesno object leaves the scope (see Arenas)
Managedreference countingnothing, optimization only
ThreadSafemarker: may be used by several threadsobjects of other allocators must not cross to another thread (Threads)
AllocatorTraitsNotes
HeapDeallocating, ThreadSafemalloc/free. Stateless: Heap() is free and carries no obligation
ArenaScoped (so AutoCloseable)bump allocator; must be closed; not thread-safe
Pool<T>(capacity)Deallocating, AutoCloseableone block size, free list; must be closed; not thread-safe
RcManaged, ThreadSafethe default of Managed code
DebugAllocator(inner)Deallocating, ThreadSafewraps another allocator and reports leaks and double frees with the allocation site at run time

Context parameters ​

An allocator is put in scope with a Kotlin context parameter. Either on a function:

kotlin
context(h: Heap)
fun load(n: Int): Buffer = Buffer(n)       // allocated from `h`

or with a block:

kotlin
context(Heap()) {                           // everything allocated in here uses this Heap
    val b = Buffer(8)
    b.free()
}

The next sample shows both. range allocates from whatever arena its caller provides; the caller decides where the nodes live:

kotlin
@file:MemoryMode(Mode.Strict)

import mini.memory.*

class Node(val value: Int, val next: Node?)

// The allocator is a context parameter: the caller decides where the nodes live.
context(a: Arena)
fun range(n: Int): Node? {
    var head: Node? = null
    for (i in n downTo 1) head = Node(i, head)
    return head
}

fun sum(list: Node?): Int {
    var total = 0
    @Borrowed var cur = list
    while (cur != null) {
        total += cur.value
        cur = cur.next
    }
    return total
}

fun main() {
    Arena().use { arena ->
        context(arena) {
            println(sum(range(4)))
        }
    }
}

The checker accepts this program, and it runs natively: it prints 10.

How an allocation site picks its allocator ​

The first rule that applies wins:

  1. A context allocator. The innermost visible context(...) of an allocator type is used. If two allocator parameters are visible at the same level (context(a: Arena, h: Heap)), the choice is ambiguous: M0114. Nest blocks instead.
  2. @AllocatedBy(X::class) on the class. This restricts rule 1 to context allocators of type X. Without a matching context, only Heap and Rc have a global default instance; Arena and Pool always need a context.
  3. The module default. In a Managed file that is Rc. In a Strict file there is none.
  4. Nothing found. If the value does not escape, the specification says it lives on the stack with no obligations (stack placement itself is not implemented yet, so today it is simply not an error). If it escapes, the compiler reports M0204.

"Escapes" means the value flows into a return, an @Owned parameter, a field, a global, an escaping lambda or another thread. Passing to a borrowed parameter and calling methods do not make a value escape.

The allocator is decided by the file or class where the class is declared, not by the caller: a Strict class constructed from Managed code still follows rules 1 and 2, and otherwise gets Rc.

@AllocatedBy ​

kotlin
@file:MemoryMode(Mode.Strict)

import mini.memory.*

@AllocatedBy(Pool::class)      // instances of Item must come from a Pool in scope
class Item(val id: Int)

fun main() {
    Pool<Item>(2).use { pool ->
        context(pool) {
            val a = Item(1)
            val b = Item(2)
            println(a.id + b.id)
            a.free()           // pool objects are freed one by one
            b.free()
        }
    }
}

Item can only be allocated from a Pool in scope. Pool objects are freed one by one (a.free()), and the pool itself is a resource that use {} closes. The checker accepts the program.

What actually happens at run time ​

Heap objects are one block with a hidden prefix that remembers the allocator they came from, so x.free() does not need to be told. Arena is a bump allocator (chunks double up to 4 MiB), Pool a fixed-size free list. The details are in The runtime.

Next: Arenas and Scoped allocators.

Released under the Apache License 2.0.