SlideShare a Scribd company logo
Clojure concurrency overview
Agenda

-Overview
-Clojure features
-Concurrent programming
-Vars
-Refs and STM approach
-Atoms
-Agents
Overview

Rich Hickey
https://twitter.com/#!/richhickey




-about 2.5 years working on Clojure
-first public release at 2007
-interview: http://www.simple-talk.com/opinion/geek-of-the-
week/rich-hickey-geek-of-the-week/
What is Clojure?

Clojure is a dynamic, LISP-like programming
       language that runs on the JVM
How does it look? Exactly! Like LISP
A form is a list where the first symbol in the
list has to be a special word that the
compiler can understand - usually the name
of a function
Clojure Features

● Functional
   ○ Immutable, persistent data structures
   ○ Functions are objects
● Lisp
● Hosted on JVM
   ○ the same memory model
   ○ garbage collector
   ○ etc
● Supporting Concurrency
● Open source
Clojure Features

● Dynamic development
   ○ REPL (read-eval-print-loop), on-the-fly
     compilation to JVM bytecode
● Full set of immutable, extensible, read-only
  data structures:
   ○ lists
   ○ maps
   ○ sets
   ○ vectors
● Macros
Clojure Features
                    Java interop



● Call java-methods, access fields
● Functions implement java.util.concurrent.
  Callable           (defn func (smthng))
● Proxy interfaces/classes
● Primitive types - int, long, byte, Char, String etc
● Clojure data structures implement Collection, Iterable,
  Comparable etc
Concurrent programming

● Things are happening at the same time
● Number of CPU is growing fast
Concurrent programming problems

Visibility problem
 ● Multiple threads use shared data
 ● 2 or more threads are trying to
   change the same data at the
   same time
Concurrent programming problems

Basic solution is
 ● locks
 ● synchronized access
 ● only one thread can have
   lock, others blocks
 ● But it requires additional efforts
     ○ thread-coordination
     ○ avoiding deadlocks
Concurrent programming problems

Access problem
 ● several threads are trying to
   access and change the same
   shared data at the same time
 ● write/read at the same time
 ● readers block readers
Clojure way

● There is no any possibility to
  change data by direct access. All
  data structures are immutable,
  remember?
● Only read, if we add element -
  new data structure will be
  created.
● No locks
● No access problems
But what if
we really want change
   data in Clojure?
     This opportunity is also
  provided by the language! All
     hard work done for us.
Reference types

● Vars
● Refs
● Atoms
● Agents
Vars

 ● Reference to mutable storage location
 ● Dynamically rebound on a per-thread basis
 ● Functions are vars, so they can be dynamically rebound too
 ● Ensure safe use via thread-isolation

(def x 5)              // root-binding
(x)                     // 5
....
(binding [x 20]
   (+ x 1))            // 21
....
(x)                     // 5 again, not changed
Changing Vars

(set! var-name new-value)
   ● cannot change root-binding
   ● works only in thread-local context (in "binding")
(def x 5)                  // root-binding
(set! x 7)                // exception will be thrown
....
(binding [x 20]
   (println (+ x 1))                // 21
   (set! x 10)
   (+ x 5))                         // 15
....
(x)                         // 5 again, not changed
Refs

● Based on Software Transactional Memory (STM)
● Change the value by applying a function to old value
● Refs can be changed within a transaction only
● Transactions will be retried automatically if conflict happens
● To make changes code must be surrounded with (dosync
  ...)
● All changes are atomic
Refs


       (def r (ref '(1 2 3)))
       (deref r)                   // list (1 2 3)

       (dosync                     // transaction begins
         ....
         (alter r                  // change ref!
              (fn [_] '(10 9 8))
         ...
       )                            // transaction ends

       (deref r)                   // list (10 9 8)
Refs lifecycle


    (def r (ref '(1 2 3)))
    (deref r)

    (dosync
      ....
                                if any other transaction
      (alter r
                                commutes - this
           (fn [_] '(10 9 8))
                                transaction is repeated
      ...
    )
                                Otherwise, that's ok and
    (deref r)                   programs continues
                                execution
Atoms

● Way to manage shared state synchronously
● Change the value by applying a function to old value
● This is done in an atomic manner by function swap!
● Internally, swap! reads the current value, appliesthe
  function to it, and attemprs to call compare-and-set! for this
  atom
Atoms best practices by Rich Hickey

(defn memoize [f]
 (let [mem (atom {})]
   (fn [& args]
     (if-let [e (find @mem args)]
       (val e)
       (let [ret (apply f args)]
         (swap! mem assoc args ret)
         ret)))))
Atoms best practices by Rich Hickey

(defn fib [n]
 (if (<= n 1)
   n
   (+ (fib (dec n)) (fib (- n 2)))))

(time (fib 35))
user=> "Elapsed time: 941.445 msecs"

(def fib (memoize fib))

(time (fib 35))

user=> "Elapsed time: 0.044 msecs"
Agents

● Asynchronous changing. They are not blocking main
  execution, return immediately
● Change the value by applying a function to old value
● Agent action dispatches take the
  form                      (send agent fn args*)
● If other actions try to change data - they will be added to
  the queue
Agents


(def a (agent 5))      // create agent
(deref a)               // 5

(send a
  (fn [old-val]
     (+ old-val 5)))
(deref a)              // may be 5, or may be 10
(Thread/sleep 1000)
(deref a)              // 10
Useful links

 ● https://groups.google.com/forum/#!forum/clojure
 ● http://clojure.org
 ● http://alexott.net/ru/clojure/index.html
 ● http://www.lisperati.com/clojure-spels/casting.html
 ● http://www.pluralsight-training.
   net/microsoft/courses/TableOfContents?
   courseName=clojure-concurrency-tutorial
Q&A

More Related Content

PDF
Clojure (and some lisp) in 10 mins for OO developers
PDF
Blocks, procs && lambdas
PPT
Clojure concurrency
PDF
Kotlin workshop 2018-06-11
PDF
Let'swift "Concurrency in swift"
PDF
05. haskell streaming io
PDF
EROSについて
PDF
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Clojure (and some lisp) in 10 mins for OO developers
Blocks, procs && lambdas
Clojure concurrency
Kotlin workshop 2018-06-11
Let'swift "Concurrency in swift"
05. haskell streaming io
EROSについて
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017

What's hot (20)

PDF
Clojure+ClojureScript Webapps
PDF
Modxpo 2015 - Custom Manager Page in MODX Revolution
ODP
Glusterd_thread_synchronization_using_urcu_lca2016
PDF
Oslo.versioned objects - Deep Dive
PPTX
Concurrency in Programming Languages
PDF
Actor Concurrency
PDF
Introduction to Redis
PDF
ConFess Vienna 2015 - Metaprogramming with Groovy
ODP
Ast transformation
PDF
'Getting' Clojure - '(parentheses are just hugs for your code)
PDF
CoffeeScript - JavaScript in a simple way
PPTX
Polymorphism in c++
PDF
Tomáš Čorej: Configuration management & CFEngine3
PDF
Introduction to clojure
PDF
Swift Tutorial 2
PDF
Using VI Java from Scala
PDF
DConf 2016: Keynote by Walter Bright
PPTX
Java8 and Functional Programming
PDF
Transactional Memory for Smalltalk
PDF
CODEsign 2015
Clojure+ClojureScript Webapps
Modxpo 2015 - Custom Manager Page in MODX Revolution
Glusterd_thread_synchronization_using_urcu_lca2016
Oslo.versioned objects - Deep Dive
Concurrency in Programming Languages
Actor Concurrency
Introduction to Redis
ConFess Vienna 2015 - Metaprogramming with Groovy
Ast transformation
'Getting' Clojure - '(parentheses are just hugs for your code)
CoffeeScript - JavaScript in a simple way
Polymorphism in c++
Tomáš Čorej: Configuration management & CFEngine3
Introduction to clojure
Swift Tutorial 2
Using VI Java from Scala
DConf 2016: Keynote by Walter Bright
Java8 and Functional Programming
Transactional Memory for Smalltalk
CODEsign 2015
Ad

Viewers also liked (6)

PPTX
Evaluation of a CIS
PDF
Graficasmatlab
PDF
Stm in-clojure
PPTX
Presentation1
Evaluation of a CIS
Graficasmatlab
Stm in-clojure
Presentation1
Ad

Similar to Clojure concurrency overview (20)

PPTX
Clojure 7-Languages
PDF
Persistent Data Structures And Managed References
KEY
Clojure Intro
ODP
Clojure basics
PDF
Stefan Kanev: Clojure, ClojureScript and Why They're Awesome at I T.A.K.E. Un...
PDF
Thinking Functionally with Clojure
PDF
Thinking Functionally - John Stevenson - Codemotion Rome 2017
PDF
I know Java, why should I consider Clojure?
PDF
Fun with Functional Programming in Clojure
PDF
Get into Functional Programming with Clojure
PDF
Get Functional Programming with Clojure
KEY
(map Clojure everyday-tasks)
PDF
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
PDF
Clojure and The Robot Apocalypse
PDF
Functional web with clojure
PDF
Functional programming with clojure
PDF
Clojure A Dynamic Programming Language for the JVM
PDF
Clojure 1.1 And Beyond
PDF
Full Stack Clojure
PDF
Clojure - An Introduction for Lisp Programmers
Clojure 7-Languages
Persistent Data Structures And Managed References
Clojure Intro
Clojure basics
Stefan Kanev: Clojure, ClojureScript and Why They're Awesome at I T.A.K.E. Un...
Thinking Functionally with Clojure
Thinking Functionally - John Stevenson - Codemotion Rome 2017
I know Java, why should I consider Clojure?
Fun with Functional Programming in Clojure
Get into Functional Programming with Clojure
Get Functional Programming with Clojure
(map Clojure everyday-tasks)
Fun with Functional Programming in Clojure - John Stevenson - Codemotion Amst...
Clojure and The Robot Apocalypse
Functional web with clojure
Functional programming with clojure
Clojure A Dynamic Programming Language for the JVM
Clojure 1.1 And Beyond
Full Stack Clojure
Clojure - An Introduction for Lisp Programmers

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Electronic commerce courselecture one. Pdf
PPTX
Cloud computing and distributed systems.
PDF
Approach and Philosophy of On baking technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
A Presentation on Artificial Intelligence
Encapsulation_ Review paper, used for researhc scholars
“AI and Expert System Decision Support & Business Intelligence Systems”
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
Spectral efficient network and resource selection model in 5G networks
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Big Data Technologies - Introduction.pptx
Unlocking AI with Model Context Protocol (MCP)
The Rise and Fall of 3GPP – Time for a Sabbatical?
MYSQL Presentation for SQL database connectivity
Electronic commerce courselecture one. Pdf
Cloud computing and distributed systems.
Approach and Philosophy of On baking technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Network Security Unit 5.pdf for BCA BBA.
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
A Presentation on Artificial Intelligence

Clojure concurrency overview

  • 3. Overview Rich Hickey https://twitter.com/#!/richhickey -about 2.5 years working on Clojure -first public release at 2007 -interview: http://www.simple-talk.com/opinion/geek-of-the- week/rich-hickey-geek-of-the-week/
  • 4. What is Clojure? Clojure is a dynamic, LISP-like programming language that runs on the JVM
  • 5. How does it look? Exactly! Like LISP
  • 6. A form is a list where the first symbol in the list has to be a special word that the compiler can understand - usually the name of a function
  • 7. Clojure Features ● Functional ○ Immutable, persistent data structures ○ Functions are objects ● Lisp ● Hosted on JVM ○ the same memory model ○ garbage collector ○ etc ● Supporting Concurrency ● Open source
  • 8. Clojure Features ● Dynamic development ○ REPL (read-eval-print-loop), on-the-fly compilation to JVM bytecode ● Full set of immutable, extensible, read-only data structures: ○ lists ○ maps ○ sets ○ vectors ● Macros
  • 9. Clojure Features Java interop ● Call java-methods, access fields ● Functions implement java.util.concurrent. Callable (defn func (smthng)) ● Proxy interfaces/classes ● Primitive types - int, long, byte, Char, String etc ● Clojure data structures implement Collection, Iterable, Comparable etc
  • 10. Concurrent programming ● Things are happening at the same time ● Number of CPU is growing fast
  • 11. Concurrent programming problems Visibility problem ● Multiple threads use shared data ● 2 or more threads are trying to change the same data at the same time
  • 12. Concurrent programming problems Basic solution is ● locks ● synchronized access ● only one thread can have lock, others blocks ● But it requires additional efforts ○ thread-coordination ○ avoiding deadlocks
  • 13. Concurrent programming problems Access problem ● several threads are trying to access and change the same shared data at the same time ● write/read at the same time ● readers block readers
  • 14. Clojure way ● There is no any possibility to change data by direct access. All data structures are immutable, remember? ● Only read, if we add element - new data structure will be created. ● No locks ● No access problems
  • 15. But what if we really want change data in Clojure? This opportunity is also provided by the language! All hard work done for us.
  • 16. Reference types ● Vars ● Refs ● Atoms ● Agents
  • 17. Vars ● Reference to mutable storage location ● Dynamically rebound on a per-thread basis ● Functions are vars, so they can be dynamically rebound too ● Ensure safe use via thread-isolation (def x 5) // root-binding (x) // 5 .... (binding [x 20] (+ x 1)) // 21 .... (x) // 5 again, not changed
  • 18. Changing Vars (set! var-name new-value) ● cannot change root-binding ● works only in thread-local context (in "binding") (def x 5) // root-binding (set! x 7) // exception will be thrown .... (binding [x 20] (println (+ x 1)) // 21 (set! x 10) (+ x 5)) // 15 .... (x) // 5 again, not changed
  • 19. Refs ● Based on Software Transactional Memory (STM) ● Change the value by applying a function to old value ● Refs can be changed within a transaction only ● Transactions will be retried automatically if conflict happens ● To make changes code must be surrounded with (dosync ...) ● All changes are atomic
  • 20. Refs (def r (ref '(1 2 3))) (deref r) // list (1 2 3) (dosync // transaction begins .... (alter r // change ref! (fn [_] '(10 9 8)) ... ) // transaction ends (deref r) // list (10 9 8)
  • 21. Refs lifecycle (def r (ref '(1 2 3))) (deref r) (dosync .... if any other transaction (alter r commutes - this (fn [_] '(10 9 8)) transaction is repeated ... ) Otherwise, that's ok and (deref r) programs continues execution
  • 22. Atoms ● Way to manage shared state synchronously ● Change the value by applying a function to old value ● This is done in an atomic manner by function swap! ● Internally, swap! reads the current value, appliesthe function to it, and attemprs to call compare-and-set! for this atom
  • 23. Atoms best practices by Rich Hickey (defn memoize [f] (let [mem (atom {})] (fn [& args] (if-let [e (find @mem args)] (val e) (let [ret (apply f args)] (swap! mem assoc args ret) ret)))))
  • 24. Atoms best practices by Rich Hickey (defn fib [n] (if (<= n 1) n (+ (fib (dec n)) (fib (- n 2))))) (time (fib 35)) user=> "Elapsed time: 941.445 msecs" (def fib (memoize fib)) (time (fib 35)) user=> "Elapsed time: 0.044 msecs"
  • 25. Agents ● Asynchronous changing. They are not blocking main execution, return immediately ● Change the value by applying a function to old value ● Agent action dispatches take the form (send agent fn args*) ● If other actions try to change data - they will be added to the queue
  • 26. Agents (def a (agent 5)) // create agent (deref a) // 5 (send a (fn [old-val] (+ old-val 5))) (deref a) // may be 5, or may be 10 (Thread/sleep 1000) (deref a) // 10
  • 27. Useful links ● https://groups.google.com/forum/#!forum/clojure ● http://clojure.org ● http://alexott.net/ru/clojure/index.html ● http://www.lisperati.com/clojure-spels/casting.html ● http://www.pluralsight-training. net/microsoft/courses/TableOfContents? courseName=clojure-concurrency-tutorial
  • 28. Q&A