软件事务内存(STM)
了解 Clojure 的 STM 如何为共享状态提供原子、一致、隔离且持久(ACID)的事务。
软件事务内存(STM) 是 CoddyKit 上的免费 Clojure Functional Programming & JVM Backend Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Clojure Functional Programming & JVM Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is Software Transactional Memory?
Imagine a bank transfer: you don't want money to disappear or appear out of thin air. You want the whole operation to succeed or fail completely.
Software Transactional Memory (STM) in Clojure provides a similar guarantee for managing shared, mutable state in concurrent programs.
- It's like a mini-database transaction system for your application's memory.
- Ensures that operations on shared data are "all or nothing."
Why We Need STM
In concurrent programming, multiple parts of your code might try to change the same piece of data at the same time. This can lead to:
- Race conditions: The outcome depends on the unpredictable timing of operations.
- Inconsistent state: Data gets corrupted or partially updated.
STM helps prevent these issues by coordinating access to shared data, ensuring data integrity.
Introducing Clojure's `Ref`s
Clojure's STM manages special data containers called Refs. Unlike regular variables, Refs are designed for transactional updates.
- A
Refholds a value that can be changed, but only within a transaction. - You create a
Refwith an initial value using(ref initial-value).
Think of a Ref as a secure vault for your data that only opens for transactions.
Atomic Updates with `dosync`
To perform operations on Refs, you must wrap them inside a dosync macro.
dosyncdefines a transaction block.- All changes to
Refs insidedosyncare treated as a single, atomic unit. - If any part of the transaction fails, all changes are rolled back.
This ensures your data remains consistent, even with concurrent access.
Modifying `Ref`s: `alter`
Inside a dosync block, you use alter to change the value of a Ref.
(alter a-ref update-fn & args)
update-fnis a function applied to the current value of theRef.& argsare additional arguments passed toupdate-fn.alterwill retry the transaction if a conflict (another transaction modifying the sameRef) is detected.
`dosync` & `alter` in Action
This example demonstrates how `dosync` and `alter` work together. We'll update a `Ref` multiple times within a transaction.
(def balance (ref 100))
(defn deposit [amount]
(dosync
(println "Current balance (inside transaction):" @balance)
(alter balance + amount)
(println "New balance (inside transaction):" @balance)))
(defn -main []
(println "Initial balance:" @balance)
(deposit 50)
(println "Final balance:" @balance))
(-main)`commute` for Independent Changes
Sometimes, the order of operations doesn't matter, like adding to a list or counting. For such operations, use commute instead of alter.
(commute a-ref update-fn & args)
commutemarks an update as "commutative."- This can reduce the chance of transaction retries, improving performance.
- It works best for operations where `(f (f x a) b)` is the same as `(f (f x b) a)`.
`commute` with Multiple Threads
Here's an example where multiple threads concurrently increment a counter using `commute`. This highlights how STM manages shared state safely and efficiently.
(def counter (ref 0))
(defn increment-counter []
(dosync
(commute counter inc)))
(defn -main []
(println "Initial counter:" @counter)
(let [futures (doall (for [_ (range 10)]
(future (dotimes [_ 100] (increment-counter)))))]
(doseq [f futures] @f)) ; Wait for all futures to complete
(println "Final counter:" @counter))
(-main)STM's ACID Guarantees
Clojure's STM provides strong guarantees, often summarized by the ACID acronym:
- Atomicity: All or nothing. A transaction either completes entirely or fails entirely.
- Consistency: Transactions bring data from one valid state to another valid state.
- Isolation: Concurrent transactions appear to execute sequentially, preventing interference.
- Durability: (Less applicable to in-memory STM directly, but implied by successful commit) Once a transaction commits, its changes are permanent.
STM Quick Check
Consider the following Clojure code snippet:
(def data (ref []))
(defn add-item [item]
(dosync
(alter data conj item)))
(add-item 10)
(add-item 20)
(println @data)What is the final output of (println @data)?
STM Recap & Beyond
In this lesson, we explored Clojure's powerful Software Transactional Memory (STM) system.
- We learned about
Refs for managing shared state. - The
dosyncmacro ensures atomic transactions. alterupdatesRefs with conflict detection and retries.commuteoptimizes updates for commutative operations.- STM provides ACID guarantees for robust concurrency.
Next, we'll look at other concurrency primitives like Promises and Futures for asynchronous operations!
常见问题解答
「软件事务内存(STM)」课时是免费的吗?
是的 — 「软件事务内存(STM)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Clojure Functional Programming & JVM Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Clojure Functional Programming & JVM Backend Development 课程共包含 4 节课。
「软件事务内存(STM)」这节课中我会学到什么?
了解 Clojure 的 STM 如何为共享状态提供原子、一致、隔离且持久(ACID)的事务。 你通过在浏览器中直接运行的动手代码来练习 Clojure Functional Programming & JVM Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Clojure Functional Programming & JVM Backend Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Clojure Functional Programming & JVM Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「软件事务内存(STM)」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Clojure Functional Programming & JVM Backend Development 课中编写并运行代码吗?
能。每节 Clojure Functional Programming & JVM Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。