English 中文(简体)
Clojure - Atoms
  • 时间:2024-11-05

Clojure - Atoms


Previous Page Next Page  

Atoms are a data type in Clojure that provide a way to manage shared, synchronous, independent state. An atom is just pke any reference type in any other programming language. The primary use of an atom is to hold Clojure’s immutable datastructures. The value held by an atom is changed with the swap! method.

Internally, swap! reads the current value, apppes the function to it, and attempts to compare-and-set it in. Since another thread may have changed the value in the intervening time, it may have to retry, and does so in a spin loop. The net effect is that the value will always be the result of the apppcation of the suppped function to a current value, atomically.

Example

Atoms are created with the help of the atom method. An example on the same is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def myatom (atom 1))
   (println @myatom))
(example)

Output

The above program produces the following result.

1

The value of atom is accessed by using the @ symbol. Clojure has a few operations that can be performed on atoms. Following are the operations.

Sr.No. Operations & Description
1 reset!

Sets the value of atom to a new value without regard for the current value.

2 compare-and-set!

Atomically sets the value of atom to the new value if and only if the current value of the atom is identical to the old value held by the atom. Returns true if set happens, else it returns false.

3 swap!

Atomically swaps the value of the atom with a new one based on a particular function.

Advertisements