0Pricing
Clojure Functional Programming & JVM Backend Development · 课时

用于状态管理的引用、代理与原子

学习使用 Clojure 的核心并发原语,在多个线程之间安全地管理可变状态。

用于状态管理的引用、代理与原子 是 CoddyKit 上的免费 Clojure Functional Programming & JVM Backend Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clojure Functional Programming & JVM Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Concurrency & State Intro

Managing state in concurrent programs is tricky! When multiple parts of your code try to change the same data at once, you can run into big problems like data corruption or deadlocks.

Clojure offers powerful tools to handle shared mutable state safely and efficiently.

Clojure's State Philosophy

Clojure embraces immutability by default. This means data structures don't change after creation. But what about when you genuinely need to change something, like a counter or a user's balance?

  • Clojure provides special concurrency primitives.
  • These primitives manage mutable state in a controlled way.
  • They ensure changes are safe, even across multiple threads.

Atoms: Independent State

An Atom is the simplest way to manage a single, independent piece of mutable state. It's great for things like counters or flags.

  • Updates are synchronous and atomic (all-or-nothing).
  • Atoms use a Compare-And-Swap (CAS) loop internally.
  • Best for state that doesn't need to be coordinated with other pieces of state.

Atom Code Example

Let's see an Atom in action. We'll create a simple counter and update it.

(ns coddykit.core
  (:gen-class))

(defn -main
  "Demonstrates Clojure Atoms."
  [& args]
  (let [my-counter (atom 0)]
    (println "Initial value:" @my-counter)

    (swap! my-counter inc)
    (println "After inc:" @my-counter)

    (swap! my-counter + 5)
    (println "After add 5:" @my-counter)))

Atom `swap!` Explained

The swap! function is key for updating Atoms:

  • It takes the atom, a function, and optional arguments for that function.
  • (swap! my-atom inc) atomically increments the value.
  • (swap! my-atom + 5) atomically adds 5 to the value.
  • The function is applied to the atom's current value, and the result becomes the new value. This happens in a thread-safe way.

Refs: Coordinated State

Refs are for managing coordinated mutable state. This means you have multiple pieces of state that must change together, or not at all.

  • Refs use Clojure's Software Transactional Memory (STM).
  • Changes occur within a transaction (dosync block).
  • All changes in a transaction either succeed or fail as a group.

Ref Code Example

Here's how to use Refs to transfer a value between two accounts atomically. If one fails, both revert.

(ns coddykit.core
  (:gen-class))

(defn -main
  "Demonstrates Clojure Refs and STM."
  [& args]
  (let [account-a (ref 100)
        account-b (ref 50)
        amount-to-transfer 20]

    (println "Initial: A=" @account-a "B=" @account-b)

    (dosync
      (alter account-a - amount-to-transfer)
      (alter account-b + amount-to-transfer))

    (println "After transfer: A=" @account-a "B=" @account-b)))

STM with Refs Explained

The dosync block defines a transaction:

  • ref creates a new Ref.
  • alter changes a Ref's value within a transaction. It takes the Ref, a function, and its arguments.
  • If any part of the dosync block fails, all changes are rolled back.
  • This ensures atomicity: all or nothing.

Agents: Asynchronous State

Agents are designed for managing mutable state asynchronously and in isolation. They're perfect for tasks that might take time or run in the background without blocking your main thread.

  • Updates are sent as messages to the Agent.
  • The Agent processes these messages in a separate thread.
  • This provides isolation: the agent's state changes only through its own processing.

Agent Code Example

Let's use an Agent to process a list of numbers asynchronously, summing them up.

(ns coddykit.core
  (:gen-class))

(defn -main
  "Demonstrates Clojure Agents."
  [& args]
  (let [sum-agent (agent 0)]
    (println "Initial sum:" @sum-agent)

    (send sum-agent + 10)
    (send sum-agent + 20)
    (send sum-agent + 5)

    (println "Waiting for agent to finish...")
    (await sum-agent) ; Wait for all sent actions to complete
    
    (println "Final sum:" @sum-agent)))

Agent Workflow

Here's how Agents work:

  • agent creates a new Agent with an initial value.
  • send dispatches a function and arguments to the agent. The function will be applied to the agent's current state on another thread.
  • The agent processes messages one by one in its own thread, ensuring isolated updates.
  • await (or await-for) is used to block the current thread until the agent has processed all pending actions.

Choosing the Right Primitive

You've learned about Atoms, Refs, and Agents. Each has a specific purpose for managing mutable state safely.

Which of the following statements correctly describe when to use which concurrency primitive?

Recap: State Management

In this lesson, we explored Clojure's core concurrency primitives for managing mutable state safely:

  • Atoms: For simple, independent, synchronous state changes.
  • Refs: For coordinated, transactional state changes across multiple values using STM.
  • Agents: For asynchronous, isolated state updates, processed in a separate thread.

Understanding these tools is crucial for building robust and concurrent Clojure applications!

常见问题解答

「用于状态管理的引用、代理与原子」课时是免费的吗?

是的 — 「用于状态管理的引用、代理与原子」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clojure Functional Programming & JVM Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。

「用于状态管理的引用、代理与原子」这节课中我会学到什么?

学习使用 Clojure 的核心并发原语,在多个线程之间安全地管理可变状态。 你通过在浏览器中直接运行的动手代码来练习 Clojure Functional Programming & JVM Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Clojure Functional Programming & JVM Backend Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Clojure Functional Programming & JVM Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「用于状态管理的引用、代理与原子」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Clojure Functional Programming & JVM Backend Development 课中编写并运行代码吗?

能。每节 Clojure Functional Programming & JVM Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 用于状态管理的引用、代理与原子
  2. 软件事务内存(STM)
  3. 承诺、未来与异步操作
  4. core.async 通道与 Go 代码块
← 返回 Clojure Functional Programming & JVM Backend Development