Clojure differences between Ref, Var, Agent, Atom, with examples

前端 未结 5 1233
孤城傲影
孤城傲影 2020-12-02 04:00

I\'m very new to Clojure, Can you guys give me explanation with real world scenarios. I mean, where to use Ref, Var, Agent, Atom. I read book, but, still couldn\'t understan

5条回答
  •  心在旅途
    2020-12-02 04:31

    I wrote article with summary up the difference between them and help choose when use which one.

    Share state - when use vars, atoms, agents and refs?

    I hope it will help people looking answers in that topic.

    Some shortcut from the article after @tunaci suggestion:

    Vars

    Vars are global for every threads.

    Do not change vars after create. It is technically possible, but it is bad idea for many reasons.

    Atoms

    Share access to mutable state for every threads. Change occurs synchronously. Retry when other thread change the state during run.

    Do not use not idempotent functions and functions with long time execution

    Agents

    Share access to mutable state for every threads. Change occurs asynchronously.

    Refs

    Refs works similar to database transactions. Write and read are protect in dosync. You can operate on many refs safe in transaction.

    And flowchart when use which one:

    Please look at the image on website, because some updates are always possible.

    It is complex and a long topic to give full answer without copy & past article, so please forgive me i redirect you to website :)

提交回复
热议问题