This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-atomicfu-memory-ordering-guardrail

Kotlin Multiplatform 2.1 AtomicFU Lock-Free Memory Ordering Invariant

Enforces strict memory ordering and publication safety invariants in Kotlin Multiplatform 2.1 lock-free data structures using AtomicFU. Prevents silent ARM64 weak memory model instruction reordering and stale cache line visibility issues across iOS Native and Android runtimes.

Prohibited Anti-Pattern: Non-Atomic Shared Mutable State and Plain Reads Bypassing AtomicFU Memory Fences on Weakly-Ordered ARM64 Architectures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 AtomicFU Lock-Free Memory Ordering Invariant - Enforces strict memory ordering and publication safety invariants in Kotlin Multiplatform 2.1 lock-free data structures using AtomicFU. Prevents silent ARM64 weak memory model instruction reordering and stale cache line visibility issues across iOS Native and Android runtimes.
globs: **/commonMain/**/*.kt, **/nativeMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-atomicfu-memory-ordering-guardrail"
---

# Kotlin Multiplatform 2.1 AtomicFU Lock-Free Memory Ordering Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Non-Atomic Shared Mutable State and Plain Reads Bypassing AtomicFU Memory Fences on Weakly-Ordered ARM64 Architectures

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform 2.1 concurrency models. Mandate lock-free memory ordering invariants across shared business logic targeting weakly-ordered ARM64 (iOS Native/Android) and sequentially consistent or TSO x86_64 host architectures. Strictly prohibit raw mutable variable leakage alongside atomic indicators, mandate CAS loops via AtomicFU update/loop primitives, and enforce immutable state container publication.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate co-dependent multi-field states into a single immutable data class held by an AtomicFU AtomicRef.
- Engineers MUST NOT mix plain `var` properties with AtomicFU primitive flags to indicate publication readiness, as ARM64 memory reordering allows reads/writes to slip past plain variable boundaries.
- Code MUST perform state transitions via AtomicFU's `loop`, `update`, or `compareAndSet` primitives to guarantee atomic read-modify-write semantics across all platform backends.
- Services MUST ensure that all instances of `atomic(...)` are private or internal and declared strictly as `private val` properties to prevent external non-synchronized mutations.
- Components NEVER expose mutable collections or mutable state instances directly from an AtomicFU reference without wrapping in read-only projections or taking explicit immutable snapshots.

## Bad vs Good Implementations
### Unsafe Piggybacking Publication vs. Atomic Immutable State Snapshot

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Writing to a non-volatile/non-atomic property `cachedToken` prior to setting an atomic flag `isInitialized` relies on memory ordering guarantees that exist on x86_64 emulators but fail on physical ARM64 hardware. iOS Native and ARM64 Android cores can reorder memory writes, allowing readers to observe `isInitialized == true` while `cachedToken` remains null or uninitialized.
```kotlin
import kotlinx.atomicfu.atomic

class SessionCoordinator {
    // ANTI-PATTERN: Plain var mutated alongside an atomic flag.
    // Weakly-ordered ARM64 cores (Apple Silicon / Android ARM) can reorder
    // the write to isInitialized before cachedToken is committed to L1/L2 cache.
    private var cachedToken: String? = null
    private val isInitialized = atomic(false)

    fun establishSession(token: String) {
        cachedToken = token
        isInitialized.value = true // Silent memory reordering hazard on native ARM64
    }

    fun getActiveToken(): String? {
        return if (isInitialized.value) {
            cachedToken // Stale read: may observe null or partially initialized reference
        } else {
            null
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: By encapsulating the token and initialized flag into an immutable `SessionState` data class and updating it via `AtomicRef.update`, AtomicFU applies the required compiler transformations, acquire-release fences, and CAS instructions across both Kotlin/Native and Kotlin/JVM, eliminating out-of-order publication hazards.
```kotlin
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update

class SessionCoordinator {
    // INVARIANT: All dependent fields are sealed in an immutable state object
    // published atomically via AtomicRef CAS operations.
    private data class SessionState(
        val token: String? = null,
        val isInitialized: Boolean = false
    )

    private val state = atomic(SessionState())

    fun establishSession(token: String) {
        state.update { current ->
            current.copy(token = token, isInitialized = true)
        }
    }

    fun getActiveToken(): String? {
        val snapshot = state.value
        return if (snapshot.isInitialized) {
            snapshot.token
        } else {
            null
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform 2.1 AtomicFU Lock-Free Memory Ordering Invariant

Kotlin Multiplatform 2.1 AtomicFU Lock-Free Memory Ordering Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory ordering and publication safety invariants in Kotlin Multiplatform 2.1 lock-free data structures using AtomicFU. Prevents silent ARM64 weak memory model instruction reordering and stale cache line visibility issues across iOS Native and Android runtimes. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Non-Atomic Shared Mutable State and Plain Reads Bypassing AtomicFU Memory Fences on Weakly-Ordered ARM64 Architectures Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftNon-Atomic Shared Mutable State and Plain Reads Bypassing AtomicFU Memory Fences on Weakly-Ordered ARM64 ArchitecturesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS encapsulate co-dependent multi-field states into a single immutable data class held by an AtomicFU AtomicRef.

Engineers MUST ALWAYS encapsulate co-dependent multi-field states into a single immutable data class held by an AtomicFU AtomicRef.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT mix plain `var` properties with AtomicFU primitive flags to indicate publication readiness, as ARM64 memory reordering allows reads/writes to slip past plain variable boundaries.

Engineers MUST NOT mix plain `var` properties with AtomicFU primitive flags to indicate publication readiness, as ARM64 memory reordering allows reads/writes to slip past plain variable boundaries.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST perform state transitions via AtomicFU's `loop`, `update`, or `compareAndSet` primitives to guarantee atomic read-modify-write semantics across all platform backends.

Code MUST perform state transitions via AtomicFU's `loop`, `update`, or `compareAndSet` primitives to guarantee atomic read-modify-write semantics across all platform backends.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that all instances of `atomic(...)` are private or internal and declared strictly as `private val` properties to prevent external non-synchronized mutations.

Services MUST ensure that all instances of `atomic(...)` are private or internal and declared strictly as `private val` properties to prevent external non-synchronized mutations.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER expose mutable collections or mutable state instances directly from an AtomicFU reference without wrapping in read-only projections or taking explicit immutable snapshots.

Components NEVER expose mutable collections or mutable state instances directly from an AtomicFU reference without wrapping in read-only projections or taking explicit immutable snapshots.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin Multiplatform 2.1 AtomicFU Lock-Free Memory Ordering Invariant critical for AI coding assistants?

Enforces strict memory ordering and publication safety invariants in Kotlin Multiplatform 2.1 lock-free data structures using AtomicFU. Prevents silent ARM64 weak memory model instruction reordering and stale cache line visibility issues across iOS Native and Android runtimes. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Non-Atomic Shared Mutable State and Plain Reads Bypassing AtomicFU Memory Fences on Weakly-Ordered ARM64 Architectures) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Kotlin