0Pricing
Clojure Functional Programming & JVM Backend Development · 강의

소프트웨어 트랜잭션 메모리(STM)

Clojure의 STM이 공유 상태에 원자성, 일관성, 격리성 및 지속성(ACID)을 갖춘 트랜잭션을 제공하는 방식을 이해합니다.

소프트웨어 트랜잭션 메모리(STM)은(는) CoddyKit의 무료 Clojure Functional Programming & JVM Backend Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 Ref holds a value that can be changed, but only within a transaction.
  • You create a Ref with 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.

  • dosync defines a transaction block.
  • All changes to Refs inside dosync are 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-fn is a function applied to the current value of the Ref.
  • & args are additional arguments passed to update-fn.
  • alter will retry the transaction if a conflict (another transaction modifying the same Ref) 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)

  • commute marks 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 dosync macro ensures atomic transactions.
  • alter updates Refs with conflict detection and retries.
  • commute optimizes 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)” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clojure Functional Programming & JVM Backend Development 강의 전체를 잠금 해제할 수 있습니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“소프트웨어 트랜잭션 메모리(STM)”에서 뭘 배우나요?

Clojure의 STM이 공유 상태에 원자성, 일관성, 격리성 및 지속성(ACID)을 갖춘 트랜잭션을 제공하는 방식을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Clojure Functional Programming & JVM Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Clojure Functional Programming & JVM Backend Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Clojure Functional Programming & JVM Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“소프트웨어 트랜잭션 메모리(STM)” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Clojure Functional Programming & JVM Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Clojure Functional Programming & JVM Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 상태 관리를 위한 Refs, Agents, Atoms
  2. 소프트웨어 트랜잭션 메모리(STM)
  3. 약속, 퓨처 및 비동기 작업
  4. core.async 채널과 Go 블록
← Clojure Functional Programming & JVM Backend Development(으)로 돌아가기