- Clojure - Libraries
- Clojure - Automated Testing
- Clojure - Applications
- Clojure - Concurrent Programming
- Clojure - Java Interface
- Clojure - Databases
- Clojure - Reference Values
- Clojure - Macros
- Clojure - Watchers
- Clojure - Agents
- Clojure - StructMaps
- Clojure - Metadata
- Clojure - Atoms
- Clojure - Date & Time
- Clojure - Destructuring
- Clojure - Predicates
- Clojure - Regular Expressions
- Clojure - Sequences
- Clojure - Exception Handling
- Clojure - Namespaces
- Clojure - Maps
- Clojure - Vectors
- Clojure - Sets
- Clojure - Lists
- Clojure - Strings
- Clojure - File I/O
- Clojure - Recursion
- Clojure - Numbers
- Clojure - Functions
- Clojure - Decision Making
- Clojure - Loops
- Clojure - Operators
- Clojure - Variables
- Clojure - Data Types
- Clojure - REPL
- Clojure - Basic Syntax
- Clojure - Environment
- Clojure - Overview
- Clojure - Home
Clojure Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Clojure - Atoms
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 | Sets the value of atom to a new value without regard for the current value. |
2 | 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 | Atomically swaps the value of the atom with a new one based on a particular function. |