I am mostly taking it easy today, it's the weekend after all, so mostly some reading of chapter 9 of Brave Clojure.
Concurrency refers to managing more than one task at the same time. It is possible to tell Clojure to do a task concurrently by placing it on a JVM thread.
(future (Thread/sleep 4000)
(println "I'll print after 4 seconds"))
(println "I'll print immediately")
As seen before in Clojure from the Ground Up, future
puts the computation in a different thread, which leaves the main thread available to process something else.
The future
function returns a reference value that you can use to request the result. This process is called dereferencing. You can do this with the deref
function or @
before the variable.
(let [result (future (println "this prints once")
(+ 1 1))]
(println "deref: " (deref result))
(println "@: " @result)); => "this prints once"; => deref: 2; => @: 2
Dereferencing will block if the future hasn't resolved the value just yet.
Something new (that I didn't know yet) is that you can place a limit on how long to wait for a future.
(deref (future (Thread/sleep 1000) 0) 10 5)
; => 5
This code tells deref to return the value 5 if the future doesn’t return a value within 10 milliseconds.
realized?
is a function that tells you if the future is done running.
Delays allow you to define a task without having to execute it or require the result immediately. You can create a delay using delay:
(delay (let [message "Just call my name and I'll be there"]
(println "First deref:" message)
message)))
To get the value you can deref
but also force
which returns it earlier.
In this case, if something is nil, it's okay, if a collection has three items it's okay, if any of its second and third element are also satisfying tree?
it's okay as well. Which gives us the following solution:
(fn tree? [xs]
(cond
(or (seq? xs) (vector? xs)) (and (= 3 (count xs)) (tree? (nth xs 1)) (tree? (nth xs 2)))
(nil? xs) true
:else false))
Let's end this (rest) day with a tally of what I completed:
- First half of Chapter 9 of Clojure for the Brave and True
- 1 4clojure problems