title: Clojure mutable storage types
body: <p>I'm attempting to learn Clojure from the API and documentation available on the site. I'm a bit unclear about mutable storage in Clojure and I want to make sure my understanding is correct. Please let me know if there are any ideas that I've gotten wrong.</p>
  
  <p>Edit: I'm updating this as I receive comments on its correctness.</p>
  
  <hr>
  
  <p><strong>Disclaimer: All of this information is informal and potentially wrong. Do not use this post for gaining an understanding of how Clojure works.</strong></p>
  
  <hr>
  
  <p><strong>Vars</strong> always contain a root binding and possibly a per-thread binding. They are comparable to regular variables in imperative languages and are not suited for sharing information between threads. <em>(thanks Arthur Ulfeldt)</em></p>
  
  <p><strong>Refs</strong> are locations shared between threads that support atomic transactions that can change the state of any number of refs in a single transaction. Transactions are committed upon exiting sync expressions (dosync) and conflicts are resolved automatically with STM magic (rollbacks, queues, waits, etc.)</p>
  
  <p><strong>Agents</strong> are locations that enable information to be asynchronously shared between threads with minimal overhead by dispatching independent action functions to change the agent's state. Agents are returned immediately and are therefore non-blocking, although an agent's value isn't set until a dispatched function has completed.</p>
  
  <p><strong>Atoms</strong> are locations that can be synchronously shared between threads. They support safe manipulation between different threads.</p>
  
  <p>Here's my friendly summary based on when to use these structures:</p>
  
  <ul>
  <li>Vars are like regular old variables in imperative languages. (avoid when possible)</li>
  <li>Atoms are like Vars but with thread-sharing safety that allows for immediate reading and safe setting. <em>(thanks Martin)</em></li>
  <li>An Agent is like an Atom but rather than blocking it spawns a new thread to calculate its value, only blocks if in the middle of changing a value, and can let other threads know that it's finished assigning.</li>
  <li>Refs are shared locations that lock themselves in transactions. Instead of making the programmer decide what happens during race conditions for every piece of locked code, we just start up a transaction and let Clojure handle all the lock conditions between the refs in that transaction.</li>
  </ul>
  
  <p>Also, a related concept is the function <code>future</code>. To me, it seems like a future object can be described as a synchronous Agent where the value can't be accessed at all until the calculation is completed. It can also be described as a non-blocking Atom. Are these accurate conceptions of future?</p>