SlideShare una empresa de Scribd logo
1 de 28
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Modxpo 2015 - Custom Manager Page in MODX Revolution
Modxpo 2015 - Custom Manager Page in MODX RevolutionModxpo 2015 - Custom Manager Page in MODX Revolution
Modxpo 2015 - Custom Manager Page in MODX Revolutionrtripault
 
Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Glusterd_thread_synchronization_using_urcu_lca2016
Glusterd_thread_synchronization_using_urcu_lca2016Atin Mukherjee
 
Oslo.versioned objects - Deep Dive
Oslo.versioned objects - Deep DiveOslo.versioned objects - Deep Dive
Oslo.versioned objects - Deep Divedavanum
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
ConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyConFess Vienna 2015 - Metaprogramming with Groovy
ConFess Vienna 2015 - Metaprogramming with GroovyIván López Martín
 
'Getting' Clojure - '(parentheses are just hugs for your code)
'Getting' Clojure - '(parentheses are just hugs for your code)'Getting' Clojure - '(parentheses are just hugs for your code)
'Getting' Clojure - '(parentheses are just hugs for your code)Gary Trakhman
 
CoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple wayCoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple wayLim Chanmann
 
Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3Tomáš Čorej: Configuration management & CFEngine3
Tomáš Čorej: Configuration management & CFEngine3Jano Suchal
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Swift Tutorial 2
Swift Tutorial  2Swift Tutorial  2
Swift Tutorial 2Jintin Lin
 
Using VI Java from Scala
Using VI Java from ScalaUsing VI Java from Scala
Using VI Java from Scaladcbriccetti
 
DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright Andrei Alexandrescu
 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional ProgrammingYiguang Hu
 
Transactional Memory for Smalltalk
Transactional Memory for SmalltalkTransactional Memory for Smalltalk
Transactional Memory for SmalltalkLukas Renggli
 

La actualidad más candente (20)

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

Destacado (6)

Design Tools
Design ToolsDesign Tools
Design Tools
 
Evaluation of a CIS
Evaluation of a CISEvaluation of a CIS
Evaluation of a CIS
 
Graficasmatlab
GraficasmatlabGraficasmatlab
Graficasmatlab
 
Stm in-clojure
Stm in-clojureStm in-clojure
Stm in-clojure
 
Sabrinappt
SabrinapptSabrinappt
Sabrinappt
 
Presentation1
Presentation1Presentation1
Presentation1
 

Similar a Clojure concurrency overview

(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojureJuan-Manuel Gimeno
 
Lcna tutorial-2012
Lcna tutorial-2012Lcna tutorial-2012
Lcna tutorial-2012Gluster.org
 
Lcna 2012-tutorial
Lcna 2012-tutorialLcna 2012-tutorial
Lcna 2012-tutorialGluster.org
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!C4Media
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Clojure and Modularity
Clojure and ModularityClojure and Modularity
Clojure and Modularityelliando dias
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overviewstasimus
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And BeyondMike Fogus
 

Similar a Clojure concurrency overview (20)

(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
Lcna tutorial-2012
Lcna tutorial-2012Lcna tutorial-2012
Lcna tutorial-2012
 
Lcna 2012-tutorial
Lcna 2012-tutorialLcna 2012-tutorial
Lcna 2012-tutorial
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Clojure and Modularity
Clojure and ModularityClojure and Modularity
Clojure and Modularity
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And Beyond
 
C language
C languageC language
C language
 

Último

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Último (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Clojure concurrency overview

  • 1.
  • 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