Grav v1.14.0

Shared

import "std/concurrency" (included in import "std") · namespace std.concurrency

State shared between threads without one lock in front of everything.

  • ThreadLocal<T>: a value per thread, made by its init the first time a thread asks. Each thread keeps its values in its own memory, so get and set take no lock: about 30 ns on one thread, and still that with many at once, where a map behind a lock slows as threads queue for it. A thread's values are let go when it exits.
  • ConcurrentMap<K, V>: a map in 16 shards, each with its own lock, so threads on different keys seldom wait for each other. merge and computeIfAbsent read and write a key in one step. Only size, keys and clear visit every shard.
  • LruCache<K, V>: at most capacity entries, forgetting the least recently used first; with ttlMs, entries also expire. A cache of 1024 entries or more is split into 16 shards (each with an equal share of the room). A hit costs about 230 ns, against 180 ns for a ConcurrentMap that never forgets; hits(), misses() and evictions() say how it is doing.
  • AtomicLong and AtomicBool are in async.
grav
import "std"

fn main() {
    let scratch = new ThreadLocal<StringBuilder>(fn() -> StringBuilder { return new StringBuilder() })
    let hits = new ConcurrentMap<string, long>()
    let threads = new Array<Thread>()
    for (t in 0..4) {
        threads.push(Thread.spawn(fn() {
            for (i in 0..100) {
                scratch.get().append("x")                       // this thread's own builder
                hits.merge(i % 2 == 0 ? "even" : "odd", 1, fn(a: long, b: long) -> long { return a + b })
            }
        }))
    }
    for (th in threads) { th.join() }
    print("${hits.get("even")} ${hits.get("odd")} ${scratch.get().length()}")
}
Output
200 200 0

LruCache

grav
import "std"

fn main() {
    let c = new LruCache<string, int>(2)
    c.put("a", 1)
    c.put("b", 2)
    print(c.getOr("a", 0))              // a is now the most recently used
    c.put("c", 3)                       // so b is forgotten to make room
    print(c.containsKey("b"))
    print(c.getOrPut("d", fn(k: string) -> int { return 4 }))
    print("${c.keys()} hits ${c.hits()} misses ${c.misses()} evicted ${c.evictions()}")
}
Output
1
false
4
["d", "c"] hits 1 misses 1 evicted 2

class ThreadLocal<T>

A value per thread: the first get() on a thread makes it with init. Each thread keeps its values in its own memory, so get and set take no lock; a thread's values are let go when it exits.

Constructors

  • new ThreadLocal(init: fn() -> T)

Methods

  • fn get() -> T — This thread's value (made by init the first time).
  • fn set(v: T) — Sets this thread's value.
  • fn has() -> bool — Whether this thread has a value yet.
  • fn remove() — Forgets this thread's value (the next get() makes a new one).

class ConcurrentMap<K, V>

A thread-safe map in 16 shards, each a HashMap with its own lock: threads on different keys seldom wait for each other, and nothing ever locks the whole map but size(), keys() and clear().

Constructors

  • new ConcurrentMap()

Methods

  • fn get(key: K) -> V
  • fn getOr(key: K, fallback: V) -> V — The value for key, or fallback.
  • fn put(key: K, value: V)
  • fn containsKey(key: K) -> bool
  • fn remove(key: K) -> bool — Removes key; whether it was there.
  • fn computeIfAbsent(key: K, make: fn(K) -> V) -> V — The value for key, made by make (once, under the key's lock) when missing.
  • fn merge(key: K, value: V, combine: fn(V, V) -> V) -> V — Puts value, or combines it with the value there (combine(old, value)); the result.
  • fn size() -> int
  • fn isEmpty() -> bool
  • fn keys() -> Array<K> — The keys at this moment (a copy).
  • fn clear()

class LruShard<K, V>

One shard of an LruCache: keys and values in parallel arrays, kept dense (a removed entry's place is taken by the last one, so nothing removed stays referenced); the recency links and expiry times in C (GravLru). Not thread-safe on its own: LruCache holds its lock.

Constructors

  • new LruShard(capacity: int)

Fields

  • capacity: int
  • hits: long = 0
  • misses: long = 0
  • evictions: long = 0

Methods

  • fn size() -> int
  • fn find(key: K, now: long) -> int — The entry's place, or -1 (expired ones are dropped; now 0: no times kept).
  • fn valueAt(i: int) -> V
  • fn getOr(key: K, now: long, fallback: V) -> V — The value for key (now the most recent), or fallback; counts the hit or miss.
  • fn put(key: K, value: V, expiresAt: long)
  • fn remove(key: K) -> bool
  • fn clear()
  • fn keys(out: Array<K>)

class LruCache<K, V>

A cache of at most capacity entries that forgets the least recently used one first; with ttlMs, entries also expire that many milliseconds after they were put. Thread-safe: a large cache (1024 entries or more) is split into 16 shards, each with its own lock and an equal share of the room, so threads seldom wait for each other (the order forgotten is then per shard).

Constructors

  • new LruCache(capacity: int, ttlMs: long = 0)

Fields

  • capacity: int
  • ttlMs: long

Methods

  • fn getOr(key: K, fallback: V) -> V — The value for key (now the most recently used), or fallback.
  • fn containsKey(key: K) -> bool — Whether key is cached (and not expired); does not count as a use.
  • fn put(key: K, value: V)
  • fn putFor(key: K, value: V, ttlMs: long) — Puts with its own time to live (0: none).
  • fn getOrPut(key: K, make: fn(K) -> V) -> V — The value for key, made by make when missing or expired (under the key's lock: make must not use this cache).
  • fn remove(key: K) -> bool — Removes key; whether it was there.
  • fn size() -> int
  • fn isEmpty() -> bool
  • fn clear()
  • fn keys() -> Array<K> — The keys, most recently used first (per shard).
  • fn hits() -> long — Lookups that found an entry, ones that did not, and entries forgotten for room.
  • fn misses() -> long
  • fn evictions() -> long

Edit this page on GitHub