Clojure - dosync



Runs the expression (in an implicit do) in a transaction that encompasses expression and any nested calls. Starts a transaction if none is already running on this thread. Any uncaught exception will abort the transaction and flow out of dosync.

Syntax

Following is the syntax.

(dosync expression)

Parameters − ‘expression’ is the set of expressions, which will come in the dosync block.

Return Value − None.

Example

An example on how this is used is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (def names (ref []))
   
   (defn change [newname]
      (dosync
         (alter names conj newname)))
   (change "John")
   (change "Mark")
   (println @names))
(Example)

Output

The above program produces the following output.

[John Mark]
clojure_reference_values.htm
Advertisements