SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
Persistent Data
  Structures and
Managed References
Clojure’s approach to Identity and State

               Rich Hickey
Agenda

• Functions and processes
• Identity, State, and Values
• Persistent Data Structures
• Clojure’s Managed References
• Q&A
Clojure Fundamentals
• Dynamic
• Functional
 • emphasis on immutability
• Supporting Concurrency
• Hosted on the JVM
 • Compiles to JVM bytecode
• Not Object-oriented
• Ideas in this talk are not Clojure- specific
Functions
• Function
 • Depends only on its arguments
 • Given the same arguments, always
    returns the same value
 • Has no effect on the world
 • Has no notion of time
Functional Programming
• Emphasizes functions
 • Tremendous benefits
• But - most programs are not functions
 • Maybe compilers, theorem provers?
   • But - They execute on a machine
   • Observably consume compute resources
Processes
• Include some notion of change over time
• Might have effects on the world
• Might wait for external events
• Might produce different answers at different
  times (i.e. have state)
• Many real/interesting programs are processes
• This talk is about one way to deal with state
  and time in the local context
State
• Value of an identity at a time
• Sounds like a variable/field?
 • Name that takes on successive ‘values’
• Not quite:
 • i=0
 • i = 42
 • j=i
 • j is 42? - depends
Variables
• Variables (and fields) in traditional
  languages are predicated on a single thread
  of control, one timeline
• Adding concurrency breaks them badly
 • Non-atomicity (e.g. of longs)
 • volatile, write visibility
 • Composite operations require locks
 • All workarounds for lack of a time model
Time
• When things happen
 • Before/after
 • Later
 • At the same time (concurrency)
 • Now
• Inherently relative
Value
• An immutable magnitude, quantity,
  number... or composite thereof
• 42 - easy to understand as value
• But traditional OO tends to make us think
  of composites as something other than
  values
 • Big mistake
  • aDate.setMonth(“January”) - ugh!
 • Dates, collections etc are all values
Identity
• A logical entity we associate with a series
  of causally related values (states) over time
• Not a name, but can be named
 • I call my mom ‘Mom’, but you wouldn’t
• Can be composite - the NY Yankees
• Programs that are processes need identity
State
• Value of an identity at a time
• Why not use variables for state?
 • Variable might not refer to a proper
    value
 • Sets of variables/fields never constitute a
    proper composite value
 • No state transition management
  • I.e., no time coordination model
Philosophy
• Things don't change in place
• Becomes obvious once you incorporate
  time as a dimension
  • Place includes time
• The future is a function of the past, and
  doesn’t change it
• Co-located entities can observe each other
  without cooperation
• Coordination is desirable in local context
Race-walker foul
      detector
• Get left foot position
 • off the ground
• Get right foot position
 • off the ground
• Must be a foul, right?
• Snapshots are critical to perception and
  decision making
• Can’t stop the runner/race (locking)
• Not a problem if we can get runner’s value
• Similarly don’t want to stop sales in order
  to calculate bonuses or sales report
Approach
• Programming with values is critical
• By eschewing morphing in place, we just
  need to manage the succession of values
  (states) of an identity
• A timeline coordination problem
 • Several semantics possible
• Managed references
 • Variable-like cells with coordination
    semantics
Persistent Data Structures
• Composite values - immutable
• ‘Change’ is merely a function, takes one value and
  returns another, ‘changed’ value
• Collection maintains its performance guarantees
  • Therefore new versions are not full copies
• Old version of the collection is still available after
  'changes', with same performance
• Example - hash map/set and vector based upon
  array mapped hash tries (Bagwell)
Bit-partitioned hash tries
Structural Sharing
• Key to efficient ‘copies’ and therefore
  persistence
• Everything is immutable so no chance of
  interference
• Thread safe
• Iteration safe
Path Copying
                                 HashMap
HashMap
                                 int count    16
int count    15
                                 INode root
INode root
Coordination Methods
•   Conventional way:

    •   Direct references to mutable objects

    •   Lock and worry (manual/convention)

•   Clojure way:

    •   Indirect references to immutable persistent data
        structures (inspired by SML’s ref)

    •   Concurrency semantics for references

        •   Automatic/enforced

        •   No locks in user code!
Typical OO - Direct
references to Mutable Objects
                               foo

                          :a          ?
                          :b          ?
                          :c         42
                          :d          ?
                          :e          6




 •   Unifies identity and value
 •   Anything can change at any time
 •   Consistency is a user problem
 •   Encapsulation doesn’t solve concurrency
     problems
Clojure - Indirect references
   to Immutable Objects
            foo                    :a     "fred"
                                   :b    "ethel"
                     @foo          :c       42
                                   :d       17
                                   :e        6




  • Separates identity and value
   • Obtaining value requires explicit
     dereference
  • Values can never change
   • Never an inconsistent value
  • Encapsulation is orthogonal
Clojure References
• The only things that mutate are references
  themselves, in a controlled way
• 4 types of mutable references, with different
  semantics:
  • Refs - shared/synchronous/coordinated
  • Agents - shared/asynchronous/autonomous
  • Atoms - shared/synchronous/autonomous
  • Vars - Isolated changes within threads
Uniform state transition
        model
 • (‘change-state’ reference function [args*])
 • function will be passed current state of the
   reference (plus any args)
 • Return value of function will be the next
   state of the reference
 • Snapshot of ‘current’ state always available
   with deref
 • No user locking, no deadlocks
Persistent ‘Edit’
                 foo               :a    "fred"
                                   :b   "ethel"
                          @foo     :c      42
                                   :d      17
                                   :e       6




                                   :a    "lucy"
                                   :b   "ethel"


•
                                   :c      42
    New value is function of old   :d      17


•
                                   :e       6
    Shares immutable structure
•   Doesn’t impede readers
•   Not impeded by readers
Atomic State Transition
              foo                   :a    "fred"
                                    :b   "ethel"
                                    :c      42
                                    :d      17
                                    :e       6

                       @foo


                                    :a    "lucy"
                                    :b   "ethel"


• Always coordinated
                                    :c      42
                                    :d      17


 • Multiple semantics
                                    :e       6



• Next dereference sees new value
• Consumers of values unaffected
Refs and Transactions
• Software transactional memory system (STM)
• Refs can only be changed within a transaction
• All changes are Atomic and Isolated
 • Every change to Refs made within a
    transaction occurs or none do
  • No transaction sees the effects of any
    other transaction while it is running
• Transactions are speculative
 • Will be retried automatically if conflict
 • Must avoid side-effects!
The Clojure STM

•   Surround code with (dosync ...), state changes
    through alter/commute, using ordinary function
    (state=>new-state)

•   Uses Multiversion Concurrency Control (MVCC)

•   All reads of Refs will see a consistent snapshot of
    the 'Ref world' as of the starting point of the
    transaction, + any changes it has made.

•   All changes made to Refs during a transaction will
    appear to occur at a single point in the timeline.
Refs in action
(def foo (ref {:a "fred" :b "ethel" :c 42 :d 17 :e 6}))

@foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6}

(assoc @foo :a "lucy")
-> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}

@foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6}

(commute foo assoc :a "lucy")
-> IllegalStateException: No transaction running

(dosync (commute foo assoc :a "lucy"))
@foo -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}
Implementation - STM
• Not a lock-free spinning optimistic design
• Uses locks, wait/notify to avoid churn
• Deadlock detection + barging
• One timestamp CAS is only global resource
• No read tracking
• Coarse-grained orientation
  • Refs + persistent data structures
•   Readers don’t impede writers/readers, writers
    don’t impede readers, supports commute
Agents
• Manage independent state
• State changes through actions, which are
  ordinary functions (state=>new-state)
• Actions are dispatched using send or send-
  off, which return immediately
• Actions occur asynchronously on thread-
  pool threads
• Only one action per agent happens at a
  time
Agents
• Agent state always accessible, via deref/@,
  but may not reflect all actions
• Any dispatches made during an action are
  held until after the state of the agent has
  changed
• Agents coordinate with transactions - any
  dispatches made during a transaction are
  held until it commits
• Agents are not Actors (Erlang/Scala)
Agents in Action
(def foo (agent {:a "fred" :b "ethel" :c 42 :d 17 :e 6}))

@foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6}

(send foo assoc :a "lucy")

@foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6}

... time passes ...

@foo -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}
Atoms
• Manage independent state
• State changes through swap!, using ordinary
  function (state=>new-state)
• Change occurs synchronously on caller thread
• Models compare-and-set (CAS) spin swap
• Function may be called more than once!
 • Guaranteed atomic transition
 • Must avoid side-effects!
Atoms in Action

(def foo (atom {:a "fred" :b "ethel" :c 42 :d 17 :e 6}))

@foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6}

(swap! foo assoc :a "lucy")

@foo -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}
Uniform state
            transition
;refs
(dosync
  (commute foo   assoc :a "lucy"))

;agents
(send foo assoc :a "lucy")

;atoms
(swap! foo assoc :a "lucy")
Summary
• Immutable values, a feature of the functional
  parts of our programs, are a critical
  component of the parts that deal with time
• Persistent data structures provide efficient
  immutable composite values
• Once you accept immutability, you can
  separate time management, and swap in
  various concurrency semantics
• Managed references provide easy to use and
  understand time coordination
Thanks for listening!



      http://clojure.org

       Questions?

Weitere ähnliche Inhalte

Andere mochten auch

Tech Success: Web/2.0 startup HOWTO
Tech Success: Web/2.0 startup HOWTOTech Success: Web/2.0 startup HOWTO
Tech Success: Web/2.0 startup HOWTOlyncis
 
WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3
WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3
WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3togelius
 
Bobcat by Noah
Bobcat by NoahBobcat by Noah
Bobcat by Noahvebrya
 
Christma activities
Christma activitiesChristma activities
Christma activitiesGavranica
 
الانتخابات المصرية
الانتخابات المصريةالانتخابات المصرية
الانتخابات المصريةnoorsabah8
 
Garden 5 9 08 Presentation7
Garden 5 9 08 Presentation7Garden 5 9 08 Presentation7
Garden 5 9 08 Presentation7themir
 
Przyjaźń międzyrodzinna
Przyjaźń międzyrodzinnaPrzyjaźń międzyrodzinna
Przyjaźń międzyrodzinnaagata stanisz
 
Sample Works
Sample WorksSample Works
Sample Worksxyndz
 
Krm Kongo Kanamal Atei Temmuz 2006
Krm Kongo Kanamal Atei Temmuz 2006Krm Kongo Kanamal Atei Temmuz 2006
Krm Kongo Kanamal Atei Temmuz 2006anttab
 
El sermón la vaca más sagrada del protestantismo
El sermón la vaca más sagrada del protestantismoEl sermón la vaca más sagrada del protestantismo
El sermón la vaca más sagrada del protestantismoPaulo Arieu
 
Product Development at the Smithsonian Libraries
Product Development at the Smithsonian LibrariesProduct Development at the Smithsonian Libraries
Product Development at the Smithsonian Librarieseclemrush
 
G1 clustering - content convergence v2 jve
G1 clustering - content convergence v2 jveG1 clustering - content convergence v2 jve
G1 clustering - content convergence v2 jveJuan V. Vidagany Espert
 
Power Point
Power PointPower Point
Power PointMJH123
 
Transient v Persistent data on Twitter
Transient v Persistent data on TwitterTransient v Persistent data on Twitter
Transient v Persistent data on TwitterPaul Johnston
 

Andere mochten auch (20)

Tech Success: Web/2.0 startup HOWTO
Tech Success: Web/2.0 startup HOWTOTech Success: Web/2.0 startup HOWTO
Tech Success: Web/2.0 startup HOWTO
 
WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3
WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3
WCCI 2008 Tutorial on Computational Intelligence and Games, part 2 of 3
 
Bobcat by Noah
Bobcat by NoahBobcat by Noah
Bobcat by Noah
 
Zendframework Parte2
Zendframework    Parte2Zendframework    Parte2
Zendframework Parte2
 
Christma activities
Christma activitiesChristma activities
Christma activities
 
الانتخابات المصرية
الانتخابات المصريةالانتخابات المصرية
الانتخابات المصرية
 
Garden 5 9 08 Presentation7
Garden 5 9 08 Presentation7Garden 5 9 08 Presentation7
Garden 5 9 08 Presentation7
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
 
Przyjaźń międzyrodzinna
Przyjaźń międzyrodzinnaPrzyjaźń międzyrodzinna
Przyjaźń międzyrodzinna
 
Sample Works
Sample WorksSample Works
Sample Works
 
βρασμός
βρασμόςβρασμός
βρασμός
 
Krm Kongo Kanamal Atei Temmuz 2006
Krm Kongo Kanamal Atei Temmuz 2006Krm Kongo Kanamal Atei Temmuz 2006
Krm Kongo Kanamal Atei Temmuz 2006
 
El sermón la vaca más sagrada del protestantismo
El sermón la vaca más sagrada del protestantismoEl sermón la vaca más sagrada del protestantismo
El sermón la vaca más sagrada del protestantismo
 
Product Development at the Smithsonian Libraries
Product Development at the Smithsonian LibrariesProduct Development at the Smithsonian Libraries
Product Development at the Smithsonian Libraries
 
Asia Youth 2009
Asia Youth 2009Asia Youth 2009
Asia Youth 2009
 
Real time web
Real time webReal time web
Real time web
 
G1 clustering - content convergence v2 jve
G1 clustering - content convergence v2 jveG1 clustering - content convergence v2 jve
G1 clustering - content convergence v2 jve
 
Power Point
Power PointPower Point
Power Point
 
Selce 2013
Selce 2013Selce 2013
Selce 2013
 
Transient v Persistent data on Twitter
Transient v Persistent data on TwitterTransient v Persistent data on Twitter
Transient v Persistent data on Twitter
 

Ähnlich wie Persistent Data Structures And Managed References

Clojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVMClojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVMelliando dias
 
FP Days: Down the Clojure Rabbit Hole
FP Days: Down the Clojure Rabbit HoleFP Days: Down the Clojure Rabbit Hole
FP Days: Down the Clojure Rabbit HoleChristophe Grand
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And ComponentsDaniel Fagnan
 
Conjfeatures
ConjfeaturesConjfeatures
Conjfeaturessmee0815
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And ComponentsDaniel Fagnan
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threadsmperham
 
Petit Humane Assessment, with Delphi
Petit Humane Assessment, with DelphiPetit Humane Assessment, with Delphi
Petit Humane Assessment, with DelphiESUG
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 
Stig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at ScaleStig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at ScaleDATAVERSITY
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Alan Christensen
 
Clojure slides
Clojure slidesClojure slides
Clojure slidesmcohen01
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Hannes Lowette
 
Pierre Livet: Ontologies, from entities to operations.
Pierre Livet: Ontologies, from entities to operations. Pierre Livet: Ontologies, from entities to operations.
Pierre Livet: Ontologies, from entities to operations. PhiloWeb
 
Into the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional ProgrammingInto the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional ProgrammingMike Pence
 
2009 training - tim m - object oriented programming
2009   training - tim m - object oriented programming2009   training - tim m - object oriented programming
2009 training - tim m - object oriented programmingTim Mahy
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design PrinciplesSerhiy Oplakanets
 
Hickey jvm summit2009
Hickey jvm summit2009Hickey jvm summit2009
Hickey jvm summit2009Kwanzoo Dev
 

Ähnlich wie Persistent Data Structures And Managed References (20)

Clojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVMClojure A Dynamic Programming Language for the JVM
Clojure A Dynamic Programming Language for the JVM
 
FP Days: Down the Clojure Rabbit Hole
FP Days: Down the Clojure Rabbit HoleFP Days: Down the Clojure Rabbit Hole
FP Days: Down the Clojure Rabbit Hole
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
 
Conjfeatures
ConjfeaturesConjfeatures
Conjfeatures
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
Petit Humane Assessment, with Delphi
Petit Humane Assessment, with DelphiPetit Humane Assessment, with Delphi
Petit Humane Assessment, with Delphi
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Stig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at ScaleStig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at Scale
 
Domain Driven Design Demonstrated
Domain Driven Design Demonstrated Domain Driven Design Demonstrated
Domain Driven Design Demonstrated
 
Clojure slides
Clojure slidesClojure slides
Clojure slides
 
HypergraphDB
HypergraphDBHypergraphDB
HypergraphDB
 
Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®Build software like a bag of marbles, not a castle of LEGO®
Build software like a bag of marbles, not a castle of LEGO®
 
Pierre Livet: Ontologies, from entities to operations.
Pierre Livet: Ontologies, from entities to operations. Pierre Livet: Ontologies, from entities to operations.
Pierre Livet: Ontologies, from entities to operations.
 
Into the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional ProgrammingInto the Land of lambda, One Programmer's Journey Into Functional Programming
Into the Land of lambda, One Programmer's Journey Into Functional Programming
 
2009 training - tim m - object oriented programming
2009   training - tim m - object oriented programming2009   training - tim m - object oriented programming
2009 training - tim m - object oriented programming
 
Javascript
JavascriptJavascript
Javascript
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles
 
Hickey jvm summit2009
Hickey jvm summit2009Hickey jvm summit2009
Hickey jvm summit2009
 

Mehr von Michael Galpin

Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in schoolMichael Galpin
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Scala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesScala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesMichael Galpin
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryMichael Galpin
 
Mobile Development 101
Mobile Development 101Mobile Development 101
Mobile Development 101Michael Galpin
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTMichael Galpin
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 

Mehr von Michael Galpin (11)

Android lessons you won't learn in school
Android lessons you won't learn in schoolAndroid lessons you won't learn in school
Android lessons you won't learn in school
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Scala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump TechnologiesScala on Android: Experiences at Bump Technologies
Scala on Android: Experiences at Bump Technologies
 
That’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your BatteryThat’s My App - Running in Your Background - Draining Your Battery
That’s My App - Running in Your Background - Draining Your Battery
 
Mobile Web 5.0
Mobile Web 5.0Mobile Web 5.0
Mobile Web 5.0
 
Mobile Development 101
Mobile Development 101Mobile Development 101
Mobile Development 101
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWT
 
Eclipse @eBay 2009
Eclipse @eBay 2009Eclipse @eBay 2009
Eclipse @eBay 2009
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Eclipse@eBay
Eclipse@eBayEclipse@eBay
Eclipse@eBay
 

Kürzlich hochgeladen

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Persistent Data Structures And Managed References

  • 1. Persistent Data Structures and Managed References Clojure’s approach to Identity and State Rich Hickey
  • 2. Agenda • Functions and processes • Identity, State, and Values • Persistent Data Structures • Clojure’s Managed References • Q&A
  • 3. Clojure Fundamentals • Dynamic • Functional • emphasis on immutability • Supporting Concurrency • Hosted on the JVM • Compiles to JVM bytecode • Not Object-oriented • Ideas in this talk are not Clojure- specific
  • 4. Functions • Function • Depends only on its arguments • Given the same arguments, always returns the same value • Has no effect on the world • Has no notion of time
  • 5. Functional Programming • Emphasizes functions • Tremendous benefits • But - most programs are not functions • Maybe compilers, theorem provers? • But - They execute on a machine • Observably consume compute resources
  • 6. Processes • Include some notion of change over time • Might have effects on the world • Might wait for external events • Might produce different answers at different times (i.e. have state) • Many real/interesting programs are processes • This talk is about one way to deal with state and time in the local context
  • 7. State • Value of an identity at a time • Sounds like a variable/field? • Name that takes on successive ‘values’ • Not quite: • i=0 • i = 42 • j=i • j is 42? - depends
  • 8. Variables • Variables (and fields) in traditional languages are predicated on a single thread of control, one timeline • Adding concurrency breaks them badly • Non-atomicity (e.g. of longs) • volatile, write visibility • Composite operations require locks • All workarounds for lack of a time model
  • 9. Time • When things happen • Before/after • Later • At the same time (concurrency) • Now • Inherently relative
  • 10. Value • An immutable magnitude, quantity, number... or composite thereof • 42 - easy to understand as value • But traditional OO tends to make us think of composites as something other than values • Big mistake • aDate.setMonth(“January”) - ugh! • Dates, collections etc are all values
  • 11. Identity • A logical entity we associate with a series of causally related values (states) over time • Not a name, but can be named • I call my mom ‘Mom’, but you wouldn’t • Can be composite - the NY Yankees • Programs that are processes need identity
  • 12. State • Value of an identity at a time • Why not use variables for state? • Variable might not refer to a proper value • Sets of variables/fields never constitute a proper composite value • No state transition management • I.e., no time coordination model
  • 13. Philosophy • Things don't change in place • Becomes obvious once you incorporate time as a dimension • Place includes time • The future is a function of the past, and doesn’t change it • Co-located entities can observe each other without cooperation • Coordination is desirable in local context
  • 14. Race-walker foul detector • Get left foot position • off the ground • Get right foot position • off the ground • Must be a foul, right?
  • 15. • Snapshots are critical to perception and decision making • Can’t stop the runner/race (locking) • Not a problem if we can get runner’s value • Similarly don’t want to stop sales in order to calculate bonuses or sales report
  • 16. Approach • Programming with values is critical • By eschewing morphing in place, we just need to manage the succession of values (states) of an identity • A timeline coordination problem • Several semantics possible • Managed references • Variable-like cells with coordination semantics
  • 17. Persistent Data Structures • Composite values - immutable • ‘Change’ is merely a function, takes one value and returns another, ‘changed’ value • Collection maintains its performance guarantees • Therefore new versions are not full copies • Old version of the collection is still available after 'changes', with same performance • Example - hash map/set and vector based upon array mapped hash tries (Bagwell)
  • 19. Structural Sharing • Key to efficient ‘copies’ and therefore persistence • Everything is immutable so no chance of interference • Thread safe • Iteration safe
  • 20. Path Copying HashMap HashMap int count 16 int count 15 INode root INode root
  • 21. Coordination Methods • Conventional way: • Direct references to mutable objects • Lock and worry (manual/convention) • Clojure way: • Indirect references to immutable persistent data structures (inspired by SML’s ref) • Concurrency semantics for references • Automatic/enforced • No locks in user code!
  • 22. Typical OO - Direct references to Mutable Objects foo :a ? :b ? :c 42 :d ? :e 6 • Unifies identity and value • Anything can change at any time • Consistency is a user problem • Encapsulation doesn’t solve concurrency problems
  • 23. Clojure - Indirect references to Immutable Objects foo :a "fred" :b "ethel" @foo :c 42 :d 17 :e 6 • Separates identity and value • Obtaining value requires explicit dereference • Values can never change • Never an inconsistent value • Encapsulation is orthogonal
  • 24. Clojure References • The only things that mutate are references themselves, in a controlled way • 4 types of mutable references, with different semantics: • Refs - shared/synchronous/coordinated • Agents - shared/asynchronous/autonomous • Atoms - shared/synchronous/autonomous • Vars - Isolated changes within threads
  • 25. Uniform state transition model • (‘change-state’ reference function [args*]) • function will be passed current state of the reference (plus any args) • Return value of function will be the next state of the reference • Snapshot of ‘current’ state always available with deref • No user locking, no deadlocks
  • 26. Persistent ‘Edit’ foo :a "fred" :b "ethel" @foo :c 42 :d 17 :e 6 :a "lucy" :b "ethel" • :c 42 New value is function of old :d 17 • :e 6 Shares immutable structure • Doesn’t impede readers • Not impeded by readers
  • 27. Atomic State Transition foo :a "fred" :b "ethel" :c 42 :d 17 :e 6 @foo :a "lucy" :b "ethel" • Always coordinated :c 42 :d 17 • Multiple semantics :e 6 • Next dereference sees new value • Consumers of values unaffected
  • 28. Refs and Transactions • Software transactional memory system (STM) • Refs can only be changed within a transaction • All changes are Atomic and Isolated • Every change to Refs made within a transaction occurs or none do • No transaction sees the effects of any other transaction while it is running • Transactions are speculative • Will be retried automatically if conflict • Must avoid side-effects!
  • 29. The Clojure STM • Surround code with (dosync ...), state changes through alter/commute, using ordinary function (state=>new-state) • Uses Multiversion Concurrency Control (MVCC) • All reads of Refs will see a consistent snapshot of the 'Ref world' as of the starting point of the transaction, + any changes it has made. • All changes made to Refs during a transaction will appear to occur at a single point in the timeline.
  • 30. Refs in action (def foo (ref {:a "fred" :b "ethel" :c 42 :d 17 :e 6})) @foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6} (assoc @foo :a "lucy") -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6} @foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6} (commute foo assoc :a "lucy") -> IllegalStateException: No transaction running (dosync (commute foo assoc :a "lucy")) @foo -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}
  • 31. Implementation - STM • Not a lock-free spinning optimistic design • Uses locks, wait/notify to avoid churn • Deadlock detection + barging • One timestamp CAS is only global resource • No read tracking • Coarse-grained orientation • Refs + persistent data structures • Readers don’t impede writers/readers, writers don’t impede readers, supports commute
  • 32. Agents • Manage independent state • State changes through actions, which are ordinary functions (state=>new-state) • Actions are dispatched using send or send- off, which return immediately • Actions occur asynchronously on thread- pool threads • Only one action per agent happens at a time
  • 33. Agents • Agent state always accessible, via deref/@, but may not reflect all actions • Any dispatches made during an action are held until after the state of the agent has changed • Agents coordinate with transactions - any dispatches made during a transaction are held until it commits • Agents are not Actors (Erlang/Scala)
  • 34. Agents in Action (def foo (agent {:a "fred" :b "ethel" :c 42 :d 17 :e 6})) @foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6} (send foo assoc :a "lucy") @foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6} ... time passes ... @foo -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}
  • 35. Atoms • Manage independent state • State changes through swap!, using ordinary function (state=>new-state) • Change occurs synchronously on caller thread • Models compare-and-set (CAS) spin swap • Function may be called more than once! • Guaranteed atomic transition • Must avoid side-effects!
  • 36. Atoms in Action (def foo (atom {:a "fred" :b "ethel" :c 42 :d 17 :e 6})) @foo -> {:d 17, :a "fred", :b "ethel", :c 42, :e 6} (swap! foo assoc :a "lucy") @foo -> {:d 17, :a "lucy", :b "ethel", :c 42, :e 6}
  • 37. Uniform state transition ;refs (dosync (commute foo assoc :a "lucy")) ;agents (send foo assoc :a "lucy") ;atoms (swap! foo assoc :a "lucy")
  • 38. Summary • Immutable values, a feature of the functional parts of our programs, are a critical component of the parts that deal with time • Persistent data structures provide efficient immutable composite values • Once you accept immutability, you can separate time management, and swap in various concurrency semantics • Managed references provide easy to use and understand time coordination
  • 39. Thanks for listening! http://clojure.org Questions?