Book Image

Clojure Programming Cookbook

Book Image

Clojure Programming Cookbook

Overview of this book

When it comes to learning and using a new language you need an effective guide to be by your side when things get rough. For Clojure developers, these recipes have everything you need to take on everything this language offers. This book is divided into three high impact sections. The first section gives you an introduction to live programming and best practices. We show you how to interact with your connections by manipulating, transforming, and merging collections. You’ll learn how to work with macros, protocols, multi-methods, and transducers. We’ll also teach you how to work with languages such as Java, and Scala. The next section deals with intermediate-level content and enhances your Clojure skills, here we’ll teach you concurrency programming with Clojure for high performance. We will provide you with advanced best practices, tips on Clojure programming, and show you how to work with Clojure while developing applications. In the final section you will learn how to test, deploy and analyze websocket behavior when your app is deployed in the cloud. Finally, we will take you through DevOps. Developing with Clojure has never been easier with these recipes by your side!
Table of Contents (16 chapters)
Clojure Programming Cookbook
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface

Solving concurrent problems using Clojure


In this recipe, we will learn Clojure's atoms, refs, and agents. Then we will have a look at Clojure's parallel features.

Getting ready

In this recipe, we will not use an external library. So, the only necessary thing is to start REPL to run code.

How to do it...

Clojure provides solutions for the concurrency problem. Clojure's vars defined in def are ensured only in single thread and are not safe in concurrent environments. Clojure provides three types of resources for concurrent problem. Here, we will introduce you atoms, refs, and agents that work in concurrent environments.

Using atoms

Atoms provide a way to manage shared, synchronous, and independent states.

Creating and referring atom

The atom function sets the initial value to atom. The following code initializes the atom to 1 and sets the atom to the var x:

(def x (atom 1)) 
;;=? #'chapter06.concurrency/x 

So, the value of x binds to Atom instance:

x 
;;=> #<Atom@541e8f8d: 1> 

To see the values...