State and Concurrency in Clojure (atom swap! ref dosync alter) vs Java (synchronized ReadWriteLock)

Поділитися
Вставка
  • Опубліковано 13 січ 2025

КОМЕНТАРІ • 9

  • @winstonsmith1585
    @winstonsmith1585 3 роки тому +1

    Great point about light-phases showing you what the phases are w/o having to understand shiftToNextPhase. Great video !

  • @elliotbarlas
    @elliotbarlas 3 роки тому +1

    Excellent comparison exercise! A simplified, data-oriented Java solution can be achieved with an enum with a value per state akin to the Clojure solution. AtomicReference can be used to safely and efficiently transition states, similar to Clojure atom. And Java synchronized blocks or methods can be used to create transactions, similar to dosync in Clojure.

    • @fredoverflow
      @fredoverflow  3 роки тому +1

      synchronized only allows 1 reader or writer at a time though.
      And ReadWriteLock blocks all readers from reading while 1 writer is writing.
      I would suggest using an AtomicReference instead.

    • @elliotbarlas
      @elliotbarlas 3 роки тому

      @@fredoverflow Good point. An AtomicReference over a collection would work as well for a lock-free implementation of the dosync Clojure code.

  • @EskoLuontola
    @EskoLuontola 3 роки тому

    A common idiom in many Clojure apps is that there is a single atom which contains the whole application state in a hashmap. It simplifies many things.

  • @erikolivier2641
    @erikolivier2641 3 роки тому

    Excellent video, thank you very much. If I could suggest another one in the same vein, it would be a translation of the dining philosopher problem from java to clojure. It is pretty straightforward in java with synchronized block and locks but I do not quite know where to start in clojure.. How could you use the locks for the forks for instance?
    Thanks again, good job

    • @fredoverflow
      @fredoverflow  3 роки тому +1

      Isn't the whole point of Dining Philosophers to demonstrate deadlocks? Clojure's Transactional Memory System uses locks internally, but detects and recovers from deadlocks automatically.
      If all you want is Clojure syntax for Java synchronization:
      (locking left-fork (locking right-fork (println "Thinking...")))

    • @erikolivier2641
      @erikolivier2641 3 роки тому +1

      @@fredoverflow This is funny. I was voluntarily trying to deadlock but couldn't do it! The irony is I am trying to deadlock in clojure but can't do it .

  • @danielwilkowski5899
    @danielwilkowski5899 2 роки тому

    Nobody in OOP would modify state in an object, they should be immutable.