---
title: Std.AtomicRef
---

Process-safe mutable references backed by ETS with a lock server.

## Types

### AtomicMutRef

```saga
opaque type AtomicMutRef a
```

Opaque handle to an atomic mutable reference. Backed by an ETS ref
with a lock server process that serializes access. Safe for use
across concurrent actors.

### LockError

```saga
type LockError =
  | LockTimeout
  deriving (Show)
```

Error type for timed lock acquisition.

## Effects

### AtomicRef

```saga
effect AtomicRef {
  fun atomic_new : a -> AtomicMutRef a
  fun atomic_lock : AtomicMutRef a -> a
  fun atomic_try_lock : AtomicMutRef a -> Int -> Result a LockError
  fun atomic_unlock : AtomicMutRef a -> a -> Unit
}
```

Atomic mutable reference effect. Provides lock-based access to
shared mutable state that is safe across concurrent processes.

## Handlers

### atomic_ref

```saga
handler atomic_ref for AtomicRef needs {Process, Monitor, Ref}
```

Lock-based handler for AtomicRef. Uses ets_ref for storage and a
serializing process for mutual exclusion. The lock server monitors
the lock holder — if the holder crashes, the lock releases automatically.

## Functions

### lock_server

```saga
fun lock_server : Unit -> Unit needs {Process, Actor LockMsg, Monitor}
```

### atomic_modify

```saga
fun atomic_modify : AtomicMutRef a -> a -> a -> a needs {AtomicRef}
```

Read-modify-write under the lock. Acquires the lock, applies the
function to the current value, writes the result, and releases.

### atomic_get

```saga
fun atomic_get : AtomicMutRef a -> a needs {AtomicRef}
```

Read the current value. Acquires and immediately releases the lock.

### atomic_set

```saga
fun atomic_set : AtomicMutRef a -> a -> Unit needs {AtomicRef}
```

Overwrite the value. Acquires the lock, writes, and releases.

