CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-clojure--clojure

Clojure core environment and runtime library providing a dynamic, general-purpose programming language on the JVM.

Pending
Overview
Eval results
Files

concurrency.mddocs/

Concurrency and State Management

Safe concurrent programming with atoms, refs, agents, and software transactional memory. Clojure provides several reference types for managing state changes in concurrent programs.

Capabilities

Atoms

Atoms provide synchronous, uncoordinated access to a single piece of state.

(atom x & options)
;; Creates atomic reference to x
;; Options: :meta metadata-map, :validator validator-fn
;; Returns: clojure.lang.Atom

(deref atom)
;; Returns current value of atom (same as @atom)
;; Returns: Object

(reset! atom newval)
;; Sets atom to newval, returns newval
;; Returns: Object

(swap! atom f & args)
;; Atomically swaps value using (f current-value args)
;; Retries if value changes during computation
;; Returns: new value

(compare-and-set! atom oldval newval)
;; Atomically sets to newval if current equals oldval
;; Returns: boolean (true if successful)

(add-watch atom key fn)
;; Adds watch function called on state changes
;; fn receives: key, atom, old-state, new-state
;; Returns: atom

(remove-watch atom key)
;; Removes watch function for key
;; Returns: atom

(set-validator! atom validator-fn)
;; Sets validator function (must return truthy for valid states)
;; Returns: atom

(get-validator atom)
;; Returns current validator function
;; Returns: function or nil

Refs and Software Transactional Memory

Refs provide coordinated, synchronous access to shared state using transactions.

(ref x & options)
;; Creates transactional reference to x
;; Options: :meta metadata-map, :validator validator-fn, :min-history int, :max-history int
;; Returns: clojure.lang.Ref

(dosync & exprs)
;; Executes expressions in transaction
;; All ref operations must occur within dosync
;; Automatically retries on conflicts
;; Returns: result of last expression

(alter ref fun & args)
;; Sets ref to (fun current-value args) within transaction
;; Must be called within dosync
;; Returns: new value

(commute ref fun & args)
;; Like alter but allows more concurrency by commuting at commit time
;; Use for commutative operations (order doesn't matter)
;; Returns: new value

(ref-set ref val)
;; Sets ref to val within transaction
;; Must be called within dosync
;; Returns: val

(ensure ref)
;; Protects ref from modification by other transactions
;; Must be called within dosync  
;; Returns: current value

(ref-history-count ref)
;; Returns number of historical values retained
;; Returns: int

(ref-min-history ref)
;; Returns minimum history count
;; Returns: int

(ref-max-history ref)  
;; Returns maximum history count
;; Returns: int

Agents

Agents provide asynchronous, independent state management.

(agent state & options)
;; Creates agent with initial state
;; Options: :meta metadata-map, :validator validator-fn, :error-handler fn, :error-mode keyword
;; Returns: clojure.lang.Agent

(send agent fn & args)
;; Queues fn for execution with agent's state
;; Uses thread pool for CPU-bound tasks
;; Returns: agent

(send-off agent fn & args)
;; Queues fn for execution with agent's state  
;; Uses expandable thread pool for I/O-bound tasks
;; Returns: agent

(await & agents)
;; Blocks until all queued actions for agents complete
;; Returns: nil

(await-for timeout-ms & agents)
;; Like await but with timeout
;; Returns: logical true if successful, nil if timeout

(agent-error agent)
;; Returns exception that caused agent to fail, nil if no error
;; Returns: Exception or nil

(clear-agent-errors agent)
;; Clears error state and restarts agent
;; Returns: agent

(restart-agent agent new-state & options)
;; Clears error and sets new state
;; Options: :clear-actions boolean
;; Returns: agent

(set-error-handler! agent handler-fn)
;; Sets error handler function  
;; handler-fn receives: agent, exception
;; Returns: agent

(error-handler agent)
;; Returns current error handler
;; Returns: function or nil

(set-error-mode! agent mode)
;; Sets error mode: :continue or :fail
;; Returns: agent

(error-mode agent)
;; Returns current error mode
;; Returns: :continue or :fail

(shutdown-agents)
;; Shuts down agent thread pools
;; Call at end of program
;; Returns: nil

Vars and Dynamic Binding

Vars provide thread-local bindings and global state management.

(var symbol)
;; Returns var object for symbol (same as #'symbol)
;; Returns: clojure.lang.Var

(binding [bindings*] & body)
;; Creates thread-local bindings for dynamic vars
;; bindings: [var-symbol value var-symbol value ...]
;; Returns: result of last body expression

(with-local-vars [bindings*] & body)
;; Creates thread-local vars
;; bindings: [symbol init-value symbol init-value ...]
;; Returns: result of last body expression

(var-get var)
;; Returns current value of var
;; Returns: Object

(var-set var val)
;; Sets thread-local value of var (must be bound)
;; Returns: val

(alter-var-root var f & args)
;; Atomically alters root value using (f current-value args)
;; Returns: new value

(with-redefs [bindings*] & body)
;; Temporarily redefines vars during body execution
;; bindings: [var-symbol temp-value var-symbol temp-value ...]
;; Returns: result of last body expression

(bound? var)
;; Returns true if var has thread-local binding
;; Returns: boolean

(thread-bound? var)
;; Returns true if var is bound to separate thread-local value
;; Returns: boolean

Delays and Promises

Utilities for delayed computation and coordination between threads.

(delay & body)
;; Creates delay object that computes body on first deref
;; Computation happens only once and result is cached
;; Returns: clojure.lang.Delay

(force delay)
;; Forces computation of delay (same as deref)
;; Returns: result of delay body

(realized? delay)
;; Returns true if delay has been computed
;; Returns: boolean

(promise)
;; Creates promise object that can be delivered once
;; Returns: clojure.lang.Promise

(deliver promise val)
;; Delivers val to promise
;; Can only be called once per promise
;; Returns: promise

(future & body)
;; Creates future that computes body in another thread
;; Returns: java.util.concurrent.Future

(future-call f)
;; Like future but calls function f with no arguments
;; Returns: java.util.concurrent.Future

(future-cancel future)
;; Attempts to cancel future
;; Returns: boolean

(future-cancelled? future)
;; Returns true if future was cancelled
;; Returns: boolean

(future-done? future)
;; Returns true if future completed
;; Returns: boolean

Usage Examples:

;; Atoms for simple state
(def counter (atom 0))
(swap! counter inc)          ; => 1
@counter                     ; => 1
(reset! counter 10)          ; => 10

;; Atoms with validation
(def positive-num (atom 1 :validator pos?))
(swap! positive-num inc)     ; => 2  
; (reset! positive-num -1)   ; Would throw exception

;; Refs for coordinated state
(def account1 (ref 100))
(def account2 (ref 200))

(defn transfer [from to amount]
  (dosync
    (alter from - amount)
    (alter to + amount)))

(transfer account1 account2 50)
[@account1 @account2]        ; => [50 250]

;; Agents for async state
(def log (agent []))
(send log conj "Starting application")
(send log conj "Loading config")
(await log)
@log                         ; => ["Starting application" "Loading config"]

;; Dynamic binding
(def ^:dynamic *debug* false)

(defn debug-print [msg]
  (when *debug*
    (println "DEBUG:" msg)))

(binding [*debug* true]
  (debug-print "This will print"))

;; Delays and promises
(def expensive-calc 
  (delay 
    (Thread/sleep 1000)
    (* 6 7)))

@expensive-calc              ; Takes 1 second, returns 42
@expensive-calc              ; Returns 42 immediately

(def p (promise))
(future (deliver p "Hello from future"))
@p                           ; => "Hello from future"

;; Futures
(def f (future 
         (Thread/sleep 1000)
         (+ 1 2 3)))

@f                           ; Blocks until complete, returns 6

Install with Tessl CLI

npx tessl i tessl/maven-org-clojure--clojure

docs

concurrency.md

control-flow.md

core-language.md

data-structures.md

data-utilities.md

dev-tools.md

formats.md

index.md

io.md

java-interop.md

math.md

sequences.md

strings.md

testing.md

tile.json